Laravel

时间:2016-06-23 03:54:09

标签: laravel

我有一个班级来建立一个关于Laravel课程注册的报告。以下是我的课程:

class Report {

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

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

    public function build() {
        // build report
    }

}

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来重构吗?

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

如果您真的需要那么多模型注入,那么您很可能需要重构代码并重新考虑如何构造Report类。

而不是模型,了解有关存储库的更多信息。

我建议您也了解有关单一责任原则的更多信息。 wiki

答案 1 :(得分:1)

由于Laravel将注入这些类的新实例,您可以考虑改为:

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

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

修改

或者这可以解决这些类的任何依赖:

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