0

recently I came across one developer's code in magento 2, where he was accessing objects in another class to avoid dependency injections.

Like for example we have Vendor\Feature\Helpler\Data class and that has one method that we use multiple places.

Vendor\Feature\Helpler\Data\Cache

<?php

declare(strict_types=1);

namespace Vendor\Feature\Helper;

use Magento\Framework\App\Helper;

class Cache extends Helper\AbstractHelper
{
    /**
     * @param $cacheId
     * @return bool|string
     */
    public function load($cacheId)
    {
        if ($this->cacheState->isEnabled(self::CACHE_ID)) {
            return $this->cache->load($cacheId);
        }
        return false;
    }
}

Now we have added this helper as dependency in the Model class with public access and we are passing this Model class's object as param in other classes, and there with this model class we are using this helper's method.

Vendor\Feature\Helper\Cache\Feature

<?php

declare(strict_types=1);

namespace Vendor\Feature\Model;

use Vendor\Feature\Helper\Cache;

class Feature extends AbstractModel
{

    public Cache $cache;

    public function __construct(
    Cache $cache
    ){
        $this->cache = $cache;
    }
}

Vendor\Feature\Model\AnotherFeature

<?php

declare(strict_types=1);

namespace Vendor\Feature\Model;

class AnotherFeature extends AbstractModel
{

    public function someMethod(Feature $feature)
    {
        $cacheId = "xyz";
        $isCached = $feature->cache->load($cacheId);
    }
}

With OOPS concepts it is fine, however, I didn't used to it much and I'm not sure this is best practice or not.

1 Answer 1

0

A helper class extending another helper class is fine but a model class should not extend helper class. You can declare a helper as a dependency inside a model. Also a class must not be too complex and must follow single responsibilty principle.

Refer below links

https://developer.adobe.com/commerce/php/best-practices/extensions/

https://m.academy/article/magento-2-model-repository-design-pattern/

2
  • thank you for your ans,I've updated the model class definition. However, my question was related something else. Like should we declare one class's property as public such that we can use it in another class , as normally to use it in another class we have to add it via di.
    – Knight017
    Commented Feb 27 at 5:40
  • We normally use child class to extend functionalities of its parent class. If classes are not directly related or remotely related to each other, then it is better to use them via di. There may be cases where you want to use properties of multiple classes in your class making the class complex and that's why multiple inheritance is not supported. Commented Feb 27 at 8:34

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.