我有一个班级来建立一个关于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来重构吗?
感谢任何帮助。
答案 0 :(得分:1)
答案 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');
...
}