다음 Larvel 5 모델에서 findByIdAndCourseOrFail
메서드는 정적이어야합니까? 컨트롤러와Laravel 모델의 사용자 정의 찾기 메소드가 정적이어야합니까?
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
}
, 우리는 제 인스턴스에 작용하지 않는 [참고보기]. 한편, 자동 의존성 주입 컨트롤러가 Laravel's service container 인 경우, $sections = $this->sections-> findByIdAndCourseOrFail(7,3);
인스턴스와 Static
인 경우 IDE (PhpStorm)가 작동합니다.
[참고] :이 의견은 Laravel Models의 작동 방식에 대한 오해 일 수 있습니다. 나에게 나는 find()
, findOrFail()
을 Class 메소드로, 따라서 find 메소드가 리턴 할 인스턴스가 아닌 Static으로 기대한다.
글쎄,'$ this'는 사용할 수 없습니다 정적 메소드. – Xorifelse
물론, 메소드가 정적으로 변경 되었다면,'$ this->'는'self ::' – Gazzer
으로 변경 될 것입니다. 그러나'where()'와'first()'는 변경이 필요할 것입니다. 그 메소드가 정의되어 있다면'Model' 전체가됩니다. – Xorifelse