directory
directory

Reputation: 3169

ZF2 routing and redirect function in controller

The following problem I am facing, error look likes this;

An error occurred
An error occurred during execution; please try again later.
Additional information:
Zend\Mvc\Exception\DomainException

File: .../vendor/zendframework/zendframework/library/Zend/Mvc/Controller/Plugin/Url.php:63

Message:
Url plugin requires that controller event compose a router; none found

I never faced this problem while I am trying to redirect from my controller. Lets say I implement the following function for redirection in my controller, which produces the error above;

public function __construct()
    {   
        # Get user identity
        $auth = new AuthenticationService();        
        if ($auth->hasIdentity()) {
        $this->identity = $auth->getIdentity();
        } else {
        $this->redirect()->toRoute('admin/login');
        }
    }

The routing does exist as I can reach site.com/admin/login/ .. login is a child of admin so notation must be good. I am wondering what's going wrong and how to fix this issue or even, where to look for it would be a great starting point as well.

Thanks!

Upvotes: 0

Views: 1219

Answers (1)

Otto Sandström
Otto Sandström

Reputation: 745

If you look at the error looks like you cant use the redirect plugin during the constructions of controller.

Url plugin requires that controller event compose a router; none found

might better to put that code in the onDispatch function like this.

public function onDispatch(MvcEvent $e)
{
    # Get user identity
    $auth = new AuthenticationService();
    if ($auth->hasIdentity()) {
        $this->identity = $auth->getIdentity();
    } else {
        return $this->redirect()->toRoute('admin/login');
    }
    return parent::onDispatch($e);
}

remember to return the redirect as otherwise the action will still be executed.

Upvotes: 2

Related Questions