如何从Symfony中的事件侦听器访问某些资源,如Doctrine或Request

时间:2016-08-27 15:19:33

标签: php symfony

版本:Symfony 3

问题:从事件侦听器的方法访问资源,例如“onKernelBefore”。

我有以下方法在调用控制器之前调用:

function onKernelController(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $controllerEvent)
    {
        $controller = $controllerEvent->getController();

        /*
         * $controller passed can be either a class or a Closure.
         * This is not usual in Symfony but it may happen.
         * If it is a class, it comes in array format
         */
        if (!is_array($controller)) {
            return;
        }
        $Helper =  new Helper();
        $current_path = $Helper->cleanSlashes($controllerEvent->getRequest()->getPathInfo());



        if ($controller[0] instanceof RouteAuthenticateInterface) {
                print "Passed";
        }
    }

但我现在不知道如何访问某些资源,例如Doctrine或Request等。我通过直接实例访问了我的助手:

$Helper =  new Helper();

虽然通常从控制器访问它,如下所示:

$this->get("Helper");

For instance I can't access this:

$this->container

我知道伪变量$this指的是控制器以外的资源;但即使我使用$controller[0]->container,我也会碰到“受保护的财产例外”。

我该怎么办?感谢

1 个答案:

答案 0 :(得分:1)

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

...

 public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
....

或者来自FOSUserBundle的更好的例子:

...
public function __construct(MailerInterface $mailer, TokenGeneratorInterface $tokenGenerator, 
            UrlGeneratorInterface $router, SessionInterface $session, Container $container)
    {
        $this->mailer = $mailer;
        $this->tokenGenerator = $tokenGenerator;
        $this->router = $router;
        $this->session = $session;
        $this->container = $container;
    }
...