Magento/*
既存のモジュールのコントローラーの動作をオーバーライドしたい。独自の実装を作成したいMagento/Customer/Controller/Account/LoginPost.php
。
- これどうやってするの?
- 依存性注入はモデル クラスにとっては良いことのように思えますが、コントローラーについてはどうでしょうか? 一部のオブジェクトが独自の実装を使用するように、独自の LoginPost コントローラー クラスをどこかに挿入できますか?
Magento/*
既存のモジュールのコントローラーの動作をオーバーライドしたい。独自の実装を作成したいMagento/Customer/Controller/Account/LoginPost.php
。
これには、 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>
という名前の新しいファイルを作成し、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;
}
}
?>
同様に、上記のクラスでbeforeExecute()
&afterExecute()
関数を使用することもできます。詳細については、このリンクをご覧ください。
調査の結果、解決策を見つけました;-)。
このリソースは非常に役に立ちました: https://github.com/tzyganu/Magento2SampleModule .
このソリューションのサンプル モジュールはこちら: https://github.com/nuclearhead/M2OverrideAction
その結果、 URI/customer/account/login
に移動すると、モジュールのデフォルト メソッドの代わりにカスタム モジュールのメソッドが起動されMagento_Customer
、URL は同じままになります。もちろん、loginPost
アクションでも同じことができます。
Router
のクラスオーバーライドでこれを行いましたdi.xml
。ソリューションを明確にするために、tzyganu の SampleNews モジュール バージョンを単純化しました。Router
クラスは、メソッドが返す URI を確認し$request->getPathInfo()
、新しい構成を次のように設定し$request
ます。
$request->setModuleName('overrideaction')
->setControllerName('view')
->setActionName('index');
$request->setDispatched(true);
$this->dispatched = true;
return $this->actionFactory->create(
'Magento\Framework\App\Action\Forward',
['request' => $request]
);
私のetc/frontend/di.xml
カスタムモジュールの:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\App\RouterList">
<arguments>
<argument name="routerList" xsi:type="array">
<item name="customer" xsi:type="array">
<item name="class" xsi:type="string">MiniSamples\OverrideAction\Controller\Router</item>
<item name="disable" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="string">9</item>
</item>
</argument>
</arguments>
</type>
</config>