7

I want to create a base controller class for all my controllers in Symfony, I am very new to Symfony, so don't be angry with dumb question. I am asking this question because I can't do something like this

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    class AbstractController extends Controller
    {
        public function __construct()
        {
            //...... check access level
            $user = $this->getUser(); //This is not working, I don't have access to the Controller(the base class) properties
        }
    }

Now one of my controllers

    class UserController extends AbstractController
    {
        public deleteUserAction(Request $request)
        {
          var_dump($this);// this will dump an empty class that is not instance of Symfony\Bundle\FrameworkBundle\Controller\Controller
          //.... delete user
        }
    }

What is the best way to do this? please... EDIT.... What I really want to do is to check whether a user privilege level is enough to access a particular action(e.g. deleteUserAction()) in a particular controller(e.g. UserController), I have a class that attach privilege level to all actions in all controllers. The check will be very efficient if it happens in a parent controller (e.g. BaseController's constructor) which is executed before UserController->deleteUserAction() but in the base controller I don't have access to $this. I have tried voter and ACL none help my situation. Thanks in advance.

Aderemi Dayo
  • 705
  • 1
  • 11
  • 25
  • What you're doing is fine inheritance-wise, although you might want to make `AbstractController` actually `abstract`. `$this instanceof Abstractcontroller` in `UserController` should return true (considering you're not using different namespaces or handling them correctly). – ccKep Mar 30 '17 at 01:25
  • 2
    You can't do anything in Controller::__construct() because the container is not yet set. Just won't work. What you can do is to create a controller listener class which will be called after the controller is fully constructed and before the controller action is called. It is a bit of an advanced topic. Might want to just check permissions in the actions to get started. http://symfony.com/doc/current/event_dispatcher.html – Cerad Mar 30 '17 at 14:14

2 Answers2

2

I think second one is the best way to create your own class and use common function in it.

If you want to add some common functions of controller then it is not the proper way to add it into the Symfony default controller, Instead you can create BaseController and extend your all the controller with BaseController and your BaseController should extends Controller.

By this way the default controller of the symfony stay untouched.

Maulik Savaliya
  • 1,262
  • 7
  • 17
1

simply use service controller... is shared:

http://symfony.com/doc/current/controller/service.html

Daniele Dolci
  • 884
  • 1
  • 9
  • 22