【问题标题】:making something similar to a constructor in a constroller Symfony 2在控制器 Symfony 2 中制作类似于构造函数的东西
【发布时间】: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 中完成吗?

【问题讨论】:

标签: php routing symfony


【解决方案1】:

至少有两种惯用的方法来实现这一点:

  1. Event listeners
  2. AOP — 在 Symfony2 中使用 JMSAopBundle

在这个用例中使用构造函数是一个坏主意™。侵入构造函数或设置器以进行与实例化对象或设置值无关的检查就是这样 - 黑客。在任何意义上,这都不合逻辑也不惯用语。这就像用头敲钉子一样——可行,但存在更好的选择。

【讨论】:

  • 为什么这是个坏主意,请告诉
  • 没有快速回答为什么它不好。但是一旦你编写了一些控制器,你可能会发现你真的不需要或不想总是执行函数。您可以使用我投反对票的答案开始。之后可能会更清楚为什么不需要它。
  • 用解释更新了我的答案。
【解决方案2】:

您可以覆盖 setContainer,它的用途与构造相同。

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

    // Your stuff
}

但您可能并不真的需要这样做。我认为随着您的设计的发展,您真的不需要检查,或者最好使用事件侦听器来完成功能。但这可以帮助您入门。

【讨论】:

  • 我只是喜欢人们在没有任何说明原因的情况下对实际答案投反对票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
  • 2011-07-26
  • 1970-01-01
相关资源
最近更新 更多