【发布时间】:2017-03-19 15:54:56
【问题描述】:
在下面的 Laravel 5 模型中,findByIdAndCourseOrFail 方法应该是静态的吗?
class Section extends Model {
//should this method be static?
public function findByIdAndCourseOrFail($id, $courseId)
{
$result = $this->where('id', $id)->where('course_id', $courseId)->first();
if (!is_null($result))
{
return $result;
}
throw (new ModelNotFoundException())->setModel(Section::class);
}
}
使用控制器:
class SectionsController extends Controller {
protected $sections;
public function __construct(Section $section)
{
$this->sections = $section;
}
public function foo($id, $courseId) //illustration only
{
$section = $this->sections->findOrFail($id);
$section = $this->sections->findByIdAndCourseOrFail($id, $courseId);
//would need to be non-static
$section = Section::findByIdAndCourseOrFail($id, $courseId);
//weird when compared with find above
}
一方面,我们没有作用于 Section 实例 [参见注释]。另一方面,在通过Laravel's service container 进行自动依赖注入的控制器中,我们将作用于一个实例:$sections = $this->sections-> findByIdAndCourseOrFail(7,3);,如果Static,我的 IDE (PhpStorm) 会发出声音。
[注意]:此评论可能是对 Laravel 模型如何工作的误解。对我来说,我希望 find()、findOrFail() 是类方法,因此是静态的,而不是 find 方法将返回的实例。
【问题讨论】:
-
好吧,
$this在静态方法中不可用。 -
当然,如果方法改成static,
$this->会改成self:: -
但是
where()和first()也需要更改,如果在其中定义了这些方法,则可能需要更改整个Model。 -
为什么 where() 和 first(0 需要更改?这些方法在 Laravel Eloquent 模型类中定义(或可访问)。
标签: php laravel methods eloquent