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