这是一个很酷的技巧。
首先创建一个特征:
<?php
namespace Application\Controller\Plugin;
use Zend\Session;
trait RefererRedirect
{
/**
* @var Session\Container
*/
private $sessionContainer;
/**
* @param Session\Container $sessionContainer
*/
public function setSessionContainer(Session\Container $sessionContainer)
{
$this->sessionContainer = $sessionContainer;
}
protected function clearReferer()
{
$this->sessionContainer->offsetUnset('referer');
}
protected function registerReferer()
{
if (!$this->sessionContainer->offsetExists('referer')) {
$this->sessionContainer->offsetSet('referer', $this->getRequest()->getHeader('Referer')->uri()->getPath());
}
}
protected function redirectToRefererOrDefaultRoute($defaultRoute, $defaultParams = [])
{
if ($this->sessionContainer->offsetExists('referer')) {
$url = $this->sessionContainer->offsetGet('referer');
$this->clearReferer();
return $this->redirect()->toUrl($url);
}
return $this->redirect()->toRoute($defaultRoute, $defaultParams);
}
}
然后是一个界面:
<?php
namespace Application;
use Zend\Session;
interface RefererAwareInterface
{
/**
* @param Session\Container $sessionContainer
*/
public function setSessionContainer(Session\Container $sessionContainer);
}
然后使用接口注入SessionContainer:
<?php
namespace Application;
class Module
{
public function getControllerConfig()
{
return [
'factories' => [
],
'initializers' => array(
function ($instance, $sm) {
if ($instance instanceof RefererAwareInterface) {
$instance->setSessionContainer(new Session\Container('Referer'));
}
}
)
];
}
}
然后在你的控制器中:
<?php
namespace Auth\Controller;
class UsersController extends AbstractActionController implements RefererAwareInterface
{
use RefererRedirect;
public function indexAction()
{
$this->clearReferer();
// do stuff
}
public function addAction()
{
$this->registerReferer();
// do stuff
return $this->redirectToRefererOrDefaultRoute('auth/users');
}
public function backAction()
{
return $this->redirectToRefererOrDefaultRoute('auth/users');
}
}