What I want:
If session is not set, I want to redirect to zf2.localhost/authUser/index
When I'm using toRoute
in CreatorController everything works.
However, I want to use this method in several files. When I attempt to call toRoute
in my SessionServiceController, I get the following error.
Error: Url plugin requires that controller event compose a router; none found
Could you write me what I'm doing wrong?
Code:
CreatorController (zf2.localhost/creator/index)
<?php
namespace Creator\Controller;
use Zend\View\Model\ViewModel;
use Zend\Mvc\Controller\AbstractActionController;
use Creator\Controller\SessionServiceController;
class CreatorController extends AbstractActionController{
public function __construct(){
$this -> sessionService = new SessionServiceController();
}
public function indexAction(){
if($this-> sessionService ->checkSession()){
echo 'Witam';
}
}
}
SessionServiceController :
<?php
namespace Creator\controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container;
use Creator\Controller\SessionServiceController;
class SessionServiceController extends AbstractActionController {
const CONTAINER_SESSION_ID = 'usr_id';
public function __construct(){
$this -> session_id = new Container( self::CONTAINER_SESSION_ID);
}
public function checkSession(){
if (empty($this ->session_id->usr_id)){
//$this->redirect()->toUrl("zf2.localhost/authUser/index");
return $this->redirect()->toRoute('creator/default',
array('controller'=>'authUser', 'action'=>'index'));
}
if (!empty($this ->session_id->usr_id)){
return true;
}
}
}
You don't want to directly instantiate your controllers, use the ServiceManager. For toRoute to work, the Url helper needs a instance of the router. This is usually handled by the ControllerPluginManager when a controller is called from the ControllerManager.
But, beyond that, this logic is probably in the wrong place. If you're checking for authenticated users, you probably want to load and utilize zend's authentication service in an event before the controller is even loaded. I would guess the best place is somewhere in your ON_ROUTE event loop, but I can't speak to your specific application.
You will know if a user is logged in or not very early in the request chain, no reason to boot a controller. Take a peek at ZfcUser ( https://github.com/ZF-Commons/ZfcUser ), it already has versions of auth redirect listeners you can use as inspiration for your own (or you might find you just want to use that project for what you're doing)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.