Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create base class for all my symfony controllers

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.

like image 887
Aderemi Dayo Avatar asked Mar 30 '17 01:03

Aderemi Dayo


2 Answers

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.

like image 139
Maulik Savaliya Avatar answered Nov 05 '22 19:11

Maulik Savaliya


simply use service controller... is shared:

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

like image 23
Daniele Dolci Avatar answered Nov 05 '22 21:11

Daniele Dolci