ここにクールなトリックがあります。
最初に特性を作成します。
<?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');
}
}