Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: how to fire code before EVERY controller-action?

I'd like to check, if the user is logged in - before the action gets called.

Something like a preDispatch() for Symfony\Bundle\FrameworkBundle\Controller\Controller would be great.

I'd like to avoid this:

class MyBaseController extends Controller {
    public function __construct() {
        // ...
        // check: logged in?
        // ...
    }
}

class MyFooController extends MyBaseController() {
    // ...
}

I just found topics from 2011/2012. I'm new to Symfony, using version 2.5 and would like to know the best-practice right from the beginning. Any advices?

Thanks in advance!

Edit:

interesting: http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html

like image 363
Mr. B. Avatar asked Oct 28 '14 20:10

Mr. B.


1 Answers

1/ You can setup before (and also after) filters with the kernel.controller Event. Here's a good example from the documentation.

  • Before Filters with the kernel.controller Event

2/ You can also create an event Listener which listens to the kernel.request event and check if the user is authenticated before targeting any controller.

It's the first event dispatched by the HttpKernel and it's mainly used to add information to the Request or return an early Response when needed (for example to deny access for non-authenticated users or users that don't have permission to access any given resource).

You can also create a listener on the kernel.controller event (as explained in the example from the documentation I listed before). This event is dispatched after the controller callable has been determined by the HttpKernel. It's mainly used to initialise things before the controller is executed, it's also used to change the controller to execute

You've to read the HttpKernel component documentation to get the big picture of how does Symfony behave internally.

3/ You can also use the @Security annotation which restricts access on controllers,

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class MyFooController extends Controller
{
    /**
     * @Security("has_role('ROLE_USER')")
     */
    public function anyAction()
    {
        // ...
like image 65
Ahmed Siouani Avatar answered Sep 18 '22 12:09

Ahmed Siouani