Search code examples
phpsymfonysymfony-3.2

Symfony: Event Subscriber prevent from Calling controller


I have made the following event subscriber:

namespace AppBundle\EventSubscriber;

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

class BeforeResolvingController implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        // return the subscribed events, their methods and priorities
        return array(
                KernelEvents::REQUEST => array(
                        array('limitVisitor',0)
                ),
        );
    }

    public function limitVisitor($e)
    {
        return new Response("Hello");
    }

}

And I have put the following in services.yml file:

app.request_subscriber:
    class: AppBundle\EventSubscriber\BeforeResolvingController
    tags:
      - { name: kernel.event_subscriber }

What I want to do is to prevent the controller to be called and directly to print the output. In the very near future an control mechanism will be implemented and I want to be able depending the case for the controller to be prevented to get called.

Do you have any idea how to do that. The code above does not seem to work. As I have seen in http://symfony.com/doc/current/components/http_kernel.html#component-http-kernel-kernel-request I am able to do that.


Solution

  • The limitVisitor method should me implemented like that:

    public function limitVisitor(GetResponseEvent $e)
    {
        $response=new Response("Hello");
        $e->setResponse($response);
    }
    

    And the message Hello will be displayed.