Magento 2.0如何在观察者中重定向

时间:2016-03-03 13:50:42

标签: php magento2

我已经为 controller_action_postdispatch 事件声明了观察者。 在excecute方法中,我检查客户是否已登录。如果不是,则应将其重定向到登录页面。

public function execute(\Magento\Framework\Event\Observer $observer)
{
  # check if user is logged in
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $customerSession = $this->objectManager->get('Magento\Customer\Model\Session');

  if(!$customerSession->isLoggedIn())
  {
    $request = $this->objectManager->get('Magento\Framework\App\Request\Http');

    if(strpos($request->getPathInfo(), '/customer/account/') !== 0)
    {
       # redirect to /customer/account/login
    }
  }
}

如何将客户端重定向到其他网址?

2 个答案:

答案 0 :(得分:5)

这是如何做到的:

public function execute(\Magento\Framework\Event\Observer $observer)
{
  # check if user is logged in
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $customerSession = $objectManager->get('Magento\Customer\Model\Session');

  if(!$customerSession->isLoggedIn())
  {
    $request = $objectManager->get('Magento\Framework\App\Request\Http');
    //get instance for URL interface
    /** @var \Magento\Framework\UrlInterface $urlInterface */
    $urlInterface = $objectManager->get('Magento\Framework\UrlInterface');
    // URL to redirect to
    $url = $urlInterface->getUrl('customer/account/login');

    if(strpos($request->getPathInfo(), '/customer/account/') !== 0)
    {
        # redirect to /customer/account/login
        $observer->getControllerAction()
         ->getResponse()
         ->setRedirect($url);
    }
  }
}

就是这样。现在它将重定向到客户登录页面。我已使用事件controller_action_predispatch

对此进行了测试

答案 1 :(得分:0)

我已尝试使用此代码从phtml页面重定向到其他页面

gem 'activeadmin', git: 'https://github.com/activeadmin/activeadmin.git'