0

I am currently creating a preference module to add additional functionality to \Magento\Catalog\Model\Product and in reviewing some of the tutorials, example below, I noted that dependencies weren't being passed to the parent constructor.

Is this just a careless omission or do the dependencies only needed to be passed to the parent constructor in certain circumstances?

<?php
namespace MyModule\ProductPreference\Model;

class Product extends \Magento\Catalog\Model\Product
{
    public function getName()
    {
        return "New Nameo";
    }
}
1

3 Answers 3

2

dependencies and constructors are conditional if you're referring to preference/overriding class.

  1. if you're using another dependencies which are not in parent class, you need to declare __construct and call parent __construct
  2. if you're not using other dependencies, you can just skip to/DO NOT delare __construct, this will automatically call parent __construct.
1

When you are extending from your parent class, it get the all things.

If you want to use new classes then you can inject them in your child class.

For more details you can get best info from there :

Magento 2 How to Override Model Class and pass the class in construct as dependency injection

1

You can use plugin

<?php

namespace Test\Catalog\Plugin;

class Product
{
    public function afterGetName(\Magento\Catalog\Model\Product $subject, $result)
    {
        return 'Test ' . $result;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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