beforeFilter函数不在Symfony2中重定向

I have implemented following code to run a code on before any action of any controller. However, the beforeFilter() function not redirecting to the route I have specified. Instead it takes the user to the location where the user clicked.

//My Listener
namespace Edu\AccountBundle\EventListener;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class BeforeControllerListener
{
    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();
        if (!is_array($controller))
        {
            //not a controller do nothing
            return;
        }
        $controllerObject = $controller[0];
        if (is_object($controllerObject) && method_exists($controllerObject, "beforeFilter"))
        //Set a predefined function to execute Before any controller Executes its any method
        {
            $controllerObject->beforeFilter();
        }
    }
}
//I have registered it already

//My Controller
class LedgerController extends Controller
{        
    public function beforeFilter()
    {   
        $commonFunction = new CommonFunctions();
        $dm = $this->getDocumentManager();
        if ($commonFunction->checkFinancialYear($dm) == 0 ) {
            $this->get('session')->getFlashBag()->add('error', 'Sorry');
            return $this->redirect($this->generateUrl('financialyear'));//Here it is not redirecting
        }
    }
}

public function indexAction() {}

Please help, What is missing in it. Thanks Advance

I would suggest you follow the Symfony suggestions for setting up before and after filters, where you perform your functionality within the filter itself, rather than trying to create a beforeFilter() function in your controller that is executed. It will allow you to achieve what you want - the function being called before every controller action - as well as not having to muddy up your controller(s) with additional code. In your case, you would also want to inject the Symfony session to the filter:

# app/config/services.yml
services:
    app.before_controller_listener:
        class: AppBundle\EventListener\BeforeControllerListener
        arguments: ['@session', '@router', '@doctrine_mongodb.odm.document_manager']
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

Then you'll create your before listener, which will need the Symony session and routing services, as well as the MongoDB document manager (making that assumption based on your profile).

// src/AppBundle/EventListener/BeforeControllerListener.php
namespace AppBundle\EventListener;

use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use AppBundle\Controller\LedgerController;
use AppBundle\Path\To\Your\CommonFunctions;

class BeforeControllerListener
{
    private $session;
    private $router;
    private $documentManager;
    private $commonFunctions;

    public function __construct(Session $session, Router $router, DocumentManager $dm)
    {
        $this->session = $session;
        $this->router = $router;
        $this->dm = $dm;
        $this->commonFunctions = new CommonFunctions();
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) {
            return;
        }

        if ($controller[0] instanceof LedgerController) {
            if ($this->commonFunctions->checkFinancialYear($this->dm) !== 0 ) {
                return;
            }

            $this->session->getFlashBag()->add('error', 'Sorry');
            $redirectUrl= $this->router->generate('financialyear');

            $event->setController(function() use ($redirectUrl) {
                return new RedirectResponse($redirectUrl);
            });
        }
    }
}

If you are in fact using the Symfony CMF then the Router might actually be ChainRouter and your use statement for the router would change to use Symfony\Cmf\Component\Routing\ChainRouter;

There are a few additional things here you might want to reconsider - for instance, if the CommonFunctions class needs DocumentManager, you might just want to make your CommonFunctions class a service that injects the DocumentManager automatically. Then in this service you would only have to inject your common functions service instead of the document manager.

Either way what is happening here is that we are checking that we are in the LedgerController, then checking whether or not we want to redirect, and if so we overwrite the entire Controller via a callback. This sets the redirect response to your route and performs the redirect.

If you want this check on every single controller you could simply eliminate the check for LedgerController. .

$this->redirect() controller function simply creates an instance of RedirectResponse. As with any other response, it needs to be either returned from a controller, or set on an event. Your method is not a controller, therefore you have to set the response on the event.

However, you cannot really set a response on the FilterControllerEvent as it is meant to either update the controller, or change it completely (setController). You can do it with other events, like the kernel.request. However, you won't have access to the controller there.

You might try set a callback with setController which would call your beforeFilter(). However, you wouldn't have access to controller arguments, so you won't really be able to call the original controller if beforeFilter didn't return a response.

Finally you might try to throw an exception and handle it with an exception listener.

I don't see why making things this complex if you can simply call your method in the controller:

public function myAction()
{
    if ($response = $this->beforeFilter()) {
        return $response;
    }

    // ....
}
public function onKernelController(FilterControllerEvent $event)
{
    $request = $event->getRequest();
    $response = new Response();

    // Matched route
    $_route  = $request->attributes->get('_route');

    // Matched controller
    $_controller = $request->attributes->get('_controller');

    $params = array(); //Your params

    $route = $event->getRequest()->get('_route');
    $redirectUrl = $url = $this->container->get('router')->generate($route,$params);


    $event->setController(function() use ($redirectUrl) {
         return new RedirectResponse($redirectUrl);
    });
}

Cheers !!