在控制器Symfony2中创建类似于构造函数的东西

时间:2012-05-07 09:23:02

标签: php routing symfony

我正在使用symfony 2进行项目。我有一个控制器,我在每个函数之前做了几次检查,我想要的是让symfony fire在每个请求控制器上运行。例如

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中完成吗?

2 个答案:

答案 0 :(得分:2)

实现这一目标至少有两种惯用方法:

  1. Event listeners
  2. AOP - 在Symfony2中使用JMSAopBundle
  3. 在这个用例中使用构造函数是一个坏主意™。攻击构造函数或setter以获取与实例化对象或设置值无关的检查只是 - 一个hack。从任何意义上说,它都不符合逻辑,也不是惯用语。这就像用头撞击钉子 - 可行,但存在更好的选择。

答案 1 :(得分:-2)

你可以覆盖setContainer,它的作用与构造相同。

public function setContainer(ContainerInterface $container = null)
{
    parent::setContainer($container);

    // Your stuff
}

但你可能不需要这样做。我认为随着您的设计的发展,您真的不需要检查,或者最好使用事件监听器来完成功能。但这可以让你开始。