2

From this website:

Manually Load Object Manager

You should avoid calling the object manager directly as this is not the proper way, but if you have to you use:

$om = \Magento\Framework\App\ObjectManager::getInstance();
/* use object manager to get a class for example the attribute repository */
$attr = $om->get('\Magento\Eav\Api\AttributeRepositoryInterface');
/* use returned class attribute repository to get the attribute id of
the name for products */
$productNameAttributeId = $attr->get('catalog_product', 'name')->getId();

It states:

this is not proper way, but if you have to you use

How can I do this the proper way?

2

The proper way is to use dependency injection in your class constructor:

protected $_attributeRepoInterface;

public function __construct(
    ...
    \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepoInterface
) {
    $this->_attributeRepoInterface = $attributeRepoInterface;
    parent::_construct(...);
}

Then later in your code, you can use the protected variable directly:

$this->_attributeRepoInterface->get('catalog_product','name')->getId();
|improve this answer|||||

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.