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.