コンストラクター整合性テスト
-
29-09-2020 - |
質問
Magento 2用の単純なCRUDモジュールを作成し、テストを実行して、何かが壊れていないかどうかを確認しています。\ nどうやら、私のモジュールには多くの問題があります。近い将来、これについていくつか質問を投稿する予定です。\ n最初の問題は、次のエラーが発生することです。
Data set: array (
0 => '\\Sample\\News\\Ui\\Component\\Listing\\Column\\AuthorActions',
)
Incorrect argument sequence in class \Sample\News\Ui\Component\Listing\Column\AuthorActions in [BASE_DIR]/app/code/Sample/News/Ui/Component/Listing/Column/AuthorActions.php
Required: $context, $uiComponentFactory, $urlBuilder, $components, $data
Actual : $urlBuilder, $context, $uiComponentFactory, $components, $data
私のクラスコンストラクタは次のようになります。
public function __construct(
\Magento\Framework\UrlInterface $urlBuilder,
\Magento\Framework\View\Element\UiComponent\ContextInterface $context,
\Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = []
)
{
$this->_urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
これは、他のクラスを拡張するすべてのクラスについて、コンストラクターパラメーターを次の順序で配置する必要があることを意味しますか?
$requiredParentParam1,
$requiredParentParam2,
...
$requiredParentParamX,
$newParam1,
$newParam2,
....
$newParamY,
$optionalParentParam1,
...
$optionalParentParamZ
そして、親クラスにない新しいクラスに追加したオプションのパラメーターをどうすればよいですか?どこに置けばいいですか?
解決
これはMagento2のドキュメントでは見つかりませんでしたが、コンストラクターを使用してクラスを拡張する場合は、最後に保持する必要があるオプションのパラメーターを除いて、パラメーターの順序を尊重する必要があります。
だから、次のことを試してみてください、それは私のために働きました:
public function __construct(
\Magento\Framework\View\Element\UiComponent\ContextInterface $context,
\Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
\Magento\Framework\UrlInterface $urlBuilder,
array $components = [],
array $data = []
)
{
$this->_urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
追加のオプションパラメータが必要な場合は、最後にそれらを配置します。
public function __construct(
\Magento\Framework\View\Element\UiComponent\ContextInterface $context,
\Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
\Magento\Framework\UrlInterface $urlBuilder,
array $components = [],
array $data = [],
array $myCustomData = []
)
{
$this->_urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
ご覧ください:
Magento\Framework\Code\Validator\ArgumentSequence::validate()
Magento\Framework\Code\Validator\ArgumentSequence::_buildsSequence()
Magento\Framework\Code\Validator\ArgumentSequence::_checkArgumentSequence()
Magento 2では、パラメーターは順序に依存するべきではありませんが、特に_checkArgumentSequence
でコードを読み取ると、これは拡張クラスには当てはまらないと思います。
つまり、順序が正しくなくても機能するはずですが、検証されていません。これは、将来のリリースのある種の互換性のために行われると思います(私の推測です)。
所属していません magento.stackexchange