在Magento2中,我们经常需要在不修改 url
结构的基础上来替换掉系统自带的 Controller
逻辑,这时我们就会用到 Controller
重写来实现这个需求,在这里我们可以通过 preference
来完成。 首先我们在模块的路由配置中创建好规则。
以我们的自建模块为例,创建并打开 Magease/HelloWorld/etc/routes.xml
在 <config>
标签内插入以下代码。
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<router id="standard">
<route id="magease" frontName="helloworld">
<module name="Magease_HelloWorld" before="Magento_Customer" />
</route>
</router>
</config>
这里我们的模块中的 controller/action
就会完全替换掉系统用户模块( Magento_Customer
)默认的 controller/action
,下面我们就需要声明我们自己的 controller/action
,新声明的 controller/action
应该继承被重写的 controller/action
并添加或者修改我们自己需要的逻辑。在这里需要注意,继承的 controller/action
必须跟被重写的 controller/action
使用完全相同的 controller
和 action
类名。
创建并打开 Magease/HelloWorld/etc/di.xml
插入以下代码。
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Customer\Controller\Account\Create" type="Magease\HelloWorld\Controller\Account\Create" />
</config>
比如我们想修改用户注册页面( Magento\Customer\Controller\Account\Create.php
)的逻辑,我们就创建一个 Magease\HelloWorld\Controller\Account\Create.php 文件并进行修改,参考下面代码:
namespace Magease\HelloWorld\Controller\Account;
use Magento\Customer\Model\Registration;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
class Create extends \Magento\Customer\Controller\AbstractAccount
{
/** @var Registration */
protected $registration;
/**
* @var Session
*/
protected $session;
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @param Context $context
* @param Session $customerSession
* @param PageFactory $resultPageFactory
* @param Registration $registration
*/
public function __construct(
Context $context,
Session $customerSession,
PageFactory $resultPageFactory,
Registration $registration
) {
$this->session = $customerSession;
$this->resultPageFactory = $resultPageFactory;
$this->registration = $registration;
parent::__construct($context);
}
/**
* Customer register form page
*
* @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
*/
public function execute()
{
if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*');
return $resultRedirect;
}
/** @var \Magento\Framework\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
return $resultPage;
}
}
好了,到此,Controller
的重写就完成了。