【发布时间】:2012-05-07 09:23:02
【问题描述】:
我正在为一个项目使用 symfony 2。我有一个控制器,在每个函数之前我都会进行几次检查,我想要的是让 symfony 在对该控制器的每个请求时触发该函数。例如
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 中完成吗?
【问题讨论】:
-
这应该是可能的,检查内核和钩子,但你可能需要稍微改变你的设计。请参阅食谱中的Event Dispatcher 和Event Dispatcher Component。