list of actions from within a controller

Hi,

Is there a way I can get a list of the actions used within a controller?

I’m using sluggable behavior in such a way that User names could conflict. ie:- user registers name as ‘Update’ and my url could then be ‘user/update’. So I thought if I could validate usernames against the list of actions within the UserController, I could avoid this occuring. (I don’t want to change the UrlManager to something like <alias>/<controller>, more human readable as <controller>/<alias>/

Thanx if you can help.

Even though my analagy can be avoided. I’d still like to know how we can get a list of actions from within a given Controller. Cheers

Hi,

you can use PHP get_class_methods function to list all functions inside Controller.


var_dump(get_class_methods($this));

http://php.net/manual/en/function.get-class-methods.php

Thank you Abed, though how to do this remotely from within a model. I’m having trouble getting the same result when I pass the Class as an attribute to a function that returns get_class_methods for that class.

ie:





    public function listControllerActions($class)

    {

        // print_r($this);die;

        return get_class_methods($class);

    }



maybe the code can not see the Controller class.

See this code:


public function listControllerActions($class)

    {

        // print_r($this);die;

        return get_class_methods($class);

    }


$model->listControllerActions("\app\controllers\yourControllerName");

Got it to work :)

$model->listControllerActions(new \frontend\controllers\UserController(‘user’, Yii::$app));

Needed to add instantiated Class with $id and $module as __construct for all Controllers. Obviously $id is lowercase name of Controller, and not so obvious to me was Yii::$app as module.

Now I can get the Actions of any controller.

Just a note though. ‘get_class_methods’ will return ALL methods, including inherited ones, and makes no distinction between them. But that is fine in my case.

Thank again for your help Abed. Hope this helps others as well.

that’s great :)

Solution with get_class_methods is only appropriate if actions were implemented like methods, but if you use actions() method to list a controller’s actions, you can simply call this method to get all controller actions.

$controller = // Get controller object as you want, from class name or whatever
$actions = array_keys($controller->actions());

Using array_keys you get only action names, you can skip array_keys usage, if you want action objects.