如何覆盖 Magento2 中的控制器?

wit*_*0ld 2 magento2

我想覆盖现有Magento/*模块的控制器行为。我想创建自己的Magento/Customer/Controller/Account/LoginPost.php实现。

  1. 我怎样才能做到这一点?
  2. 依赖注入对于模型类来说似乎是件好事,但是控制器呢?我可以在某处注入我自己的 LoginPost 控制器类,以便某些对象使用我自己的实现吗?

Muk*_*ain 6

您可以为此使用Magento2 的插件功能。

Magento 使您能够更改或扩展任何 Magento 类中任何原始公共方法的行为。您可以通过创建扩展来更改原始方法的行为。这些扩展使用Plugin类,因此被称为插件。

在您的模块app/code/YourNamespace/YourModule/etc/di.xml文件中写入以下内容:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">    
   <type name="Magento\Customer\Controller\Account\LoginPost">
       <plugin name="yourModuleAccountLoginPost" type="YourNamespace\YourModule\Plugin\Customer\LoginPost" sortOrder="10" disabled="false"/>
   </type>
</config>
Run Code Online (Sandbox Code Playgroud)

创建一个名为的新文件app/code/YourNamespace/YourModule/Plugin/Customer/LoginPost.php并在其中写入以下代码:

<?php

    namespace YourNamespace\YourModule\Plugin\Customer;

    class LoginPost
    {
        public function aroundExecute(\Magento\Customer\Controller\Account\LoginPost $subject, \Closure $proceed)
        {
            // your custom code before the original execute function
            $this->doSomethingBeforeExecute();

            // call the original execute function
            $returnValue = $proceed();

            // your custom code after the original execute function
            if ($returnValue) {
                $this->doSomethingAfterExecute();
            }

            return $returnValue;
        }
    }
?>
Run Code Online (Sandbox Code Playgroud)

同样,你也可以在上面的类中使用beforeExecute()&afterExecute()函数。请查看此链接以了解详细信息。