3

I've noticed strange situation while creating class contructor (__construct).

Here is my code:

public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
        \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
        array $data = []
    )

And:

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
        \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        array $data = []
    )

In first case it returns Internal Server Error 500, but in second case all works fine.

Why does agruments order affects?

Thanks in advance!

  • May be you extend specific class? – Vladyslav Sep 14 '17 at 21:35
  • @Vladyslav I extend AbstractModel class – Kyrylo Romantsov Sep 15 '17 at 9:44
3

Optional parameters MUST be going after the required.

If you omit this rule your code will depend on concrete implementation, because you need to know all default values for optional parameters that can be different in other implementations. This breaks Liskov substitution principle.

It's why the first example does not work.

| improve this answer | |
  • Do you know why $data comes last instead of in the order of the parent? – linden2015 Sep 21 '17 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.