Zend certified PHP/Magento developer

Magento 2 Coding Practice

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 VendorFeatureHelplerData class and that has one method that we use multiple places.

VendorFeatureHelplerDataCache

<?php

declare(strict_types=1);

namespace VendorFeatureHelper;

use MagentoFrameworkAppHelper;

class Cache extends HelperAbstractHelper
{
    /**
     * @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.

VendorFeatureHelperCacheFeature

<?php

declare(strict_types=1);

namespace VendorFeatureModel;

use VendorFeatureHelperCache;

class Feature extends HelperAbstractHelper
{

    public Cache $cache;

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

VendorFeatureModelAnotherFeature

<?php

declare(strict_types=1);

namespace VendorFeatureModel;

class AnotherFeature extends HelperAbstractHelper
{

    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.