Diyar Baban Diyar Baban -4 years ago 67
PHP Question

Find out called method name in class constructor?

Is it possible to get the name of a called method in a class from the

__construct()
function?

I have an MVC application where users have permissions, and for a user to access a specific route (method) in a controller (class) they must have certain permissions which I want to define in the controller's constructor method because I don't want to clutter my controllers with repetitive code just to check if a user has a certain permission in every method.

Answer Source

Is it possible to get the name of a called method in a class from the __construct() function?

No. The constructor is not invoked when you call the method, it's invoked when you create an instance of the object. So, by the time you call the method, the constructor has already completed.

I want to define in the controller's constructor method because I don't want to clutter my controllers with repetitive code just to check if a user has a certain permission in every method.

In this case, you could make a protected function that does your permission checking, and then call that from each of the public route methods:

class Controller
{

    protected function checkPermissions($route)
    {
        // ...
    }

    public function someRoute()
    {
        $this->checkPermissions(__METHOD__);
        // ...
    }

    public function someOtherRoute()
    {
        $this->checkPermissions(__METHOD__);
        // ...
    }

}

Or better, you probably have some other code that automatically instantiates the Controller object and then looks for the correct method to fire. If so, you can add the call to check permissions to that code block, and then you don't have to touch the route methods at all:

$controllerName = // determined by analyzing URL;
$routeName = // determined by analyzing URL;
if (!class_exists($controllerName)) {
    throw new Exception('no such controller');
}
$controller = new $controllerName();
if (!method_exists($controller, $routeName)) {
    throw new Exception('no such route in controller');
}
$controller->checkPermissions($routeName);
$controller->$routeName();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download