2016-06-23 8 views
2

私はLaravelのコース登録に関するレポートを作成するクラスを持っています。以下は私のクラスです:Laravelの集計注射

Laravelは、ユーザー、コース、および登録モデルのインスタンスをレポートに自動的に挿入します。 レポートを作成するために使用する必要がある他のModelクラスがもっと必要な場合は、Reportのコンストラクタにさらに引数を追加する必要があります。

class Report { 

    protected $user; 
    protected $course; 
    protected $registration; 

    public function __construct(User $user, Course $course, Registration $registration, Another1 $another1, Another2 $another2, ...) { 
     $this->user = $user; 
     $this->course = $course; 
     $this->registration = $registration; 
    } 

    public function build() { 
     // build report 
    } 

} 

これは正しい方法ですか? Reportクラスで使用されるクラスを集約する他の方法はありますか? Facade Patternを使用してリファクタリングする必要がありますか?

何か助けていただければ幸いです。

答えて

1

実際に多くのモデル注入が必要な場合は、コードをリファクタリングして、Reportクラスの構築方法を再検討する必要があるようです。

モデルの代わりに、リポジトリについて学んでください。

また、単一責任の原則についてさらに知ることをお勧めします。

public function __construct() 
{ 
    $this->createInstances(); 
} 

protected function createInstances() 
{ 
    $this->user = new User; 
    $this->course = new Course; 
    $this->registration = new Registration; 
    ... 
} 

EDITwiki

1

Laravelは、これらのクラスの新しいインスタンスを注入しますので、あなたが代わりにこれを行うことを検討することができます

それともこれは、これらのクラスのいずれかの依存関係を解決するために:

protected function createInstances() 
{ 
    $this->user = $this->app->make('User'); 
    $this->course = $this->app->make('Course'); 
    $this->registration = $this->app->make('Registration'); 
    ... 
}