Search code examples
laminas

How to get action name in Laminas framework constructor


Getting the action name within an action is simple - I can use the "actionName" parameter. But is there a way to get the action name in the constructor of the Controller?

    public function __construct()
    {
        parent::__construct();
        $action = $this->params('actionName');
    }

Solution

  • The constructor in the Controller-Class does not know yet which action is called. However, You could extend the onDispatch-method in the AbstractActionController.php which is called before any action is called but after the __construct()-method is called. Something like this:

    <?php
    ...
    use Laminas\Mvc\MvcEvent; # <-- add this
    
    class YourController extends AbstractActionController
    {
        
        public function onDispatch(MvcEvent $e)
        {
            $this->action = $this->params()->fromRoute('action');
    
            // Or somethink like e.g.:
            if ($this->params()->fromRoute('action') == 'foo') {
              // do something
            }
    
            return parent::onDispatch($e);
            
        }
    }