magento2里如何在Observer里设置跳转

3.71K 浏览开发笔记

magento2里如何在Observer里设置跳转

m2里经常会用到event(observer)里监听事件,进行逻辑处理。

1,直接跳转

$controller = $observer->getControllerAction();
$this->redirect->redirect($controller->getResponse(), 'customer/account/login');

2,在原页面进行跳转 (得到原页面的controlleraction,替换response内容即可)

$controller = $observer->getControllerAction();
$url = $this->getUrl('customer/account/login'); //MagentoFrameworkUrlInterface $url
$controller->getResponse()->setRedirect($url);

以直接跳转为例,代码如下:

<?php
namespace MagentoCaptchaObserver;
use MagentoFrameworkEventObserverInterface;
class CheckForgotpasswordObserver implements ObserverInterface
{
    protected $redirect;
    public function __construct(
        MagentoFrameworkAppResponseRedirectInterface $redirect
    ) {
        $this->redirect = $redirect;
    }
    /**
     * Redirect to login page
     *
     * @param MagentoFrameworkEventObserver $observer
     * @return $this
     */
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        /** @var MagentoFrameworkAppActionAction $controller */
        $controller = $observer->getControllerAction();
        $this->redirect->redirect($controller->getResponse(), 'customer/account/login');
        return $this;
    }
}

0