我使用的symfony 2爲一個項目類似構造函數的東西。我有一個控制器,我每個功能之前進行多次檢查什麼,我要的是讓symfony的大火,在該控制器每個請求的功能。例如使得在constroller Symfony的2
class ChatController extends Controller
{
public function put()
{
$user = $this->getUser();
$this->checkSomething(); //just a custom function
$this->checkSomethingElse(); //another custom function
// do something
}
public function get()
{
$user = $this->getUser();
$this->checkSomething(); //just a custom function
$this->checkSomethingElse(); //another custom function
// do something
}
}`
我想達到同樣的事情:
class ChatController extends Controller
{
private $user;
public function init()
{
$this->user = $this->getUser();
$this->checkSomething(); //just a custom function
$this->checkSomethingElse(); //another custom function
}
public function put()
{
//here i can access $this->user
// do something
}
public function get()
{
//here i can access $this->user
// do something
}
}`
所以基本上我想要的是讓一個函數像一個構造函數。這可以在Symfony2中完成嗎?
這應該是可能的,檢查內核和掛鉤,但你可能需要改變你的設計了一下。請參閱食譜和[事件調度程序組件](http://symfony.com/doc/current/components)中的[Event Dispatcher](http://symfony.com/doc/current/cookbook/event_dispatcher/index.html) /event_dispatcher/index.html)。 – hakre