2
我只想知道在我的PostController中创建构造函数是否可以?Laravel 4控制器构造函数
例1:
public class PostController extends BaseController
{
protected $posts;
//Is this ok?
public function __construct(Post $posts){
$this->posts = $posts;
}
public function getPosts(){
$posts = $this->posts->all();
return View::make('get-index',compact('posts'))
}
}
任何理由,你为什么认为它不应该是什么?虽然'$ this-> posts = $ posts;'在你的构造函数中是没有意义的 – 2014-10-01 08:26:19
你确实可以使用构造函数。然而,Laravel喜欢使用称为依赖注入的东西来初始化控制器。你应该添加一个参数到你的控制器的构造函数中,如下所示:'public function __construct(Post $ post){' – Jonathon 2014-10-01 08:27:01
当然,我忘了给它发布obj作为参数:) – Spoofy 2014-10-01 08:27:45