<aside> ➡️ The pages under the Engineering page are currently curated by the company's chief technical officer (CTO). To contribute, please leave a comment. How to comment?
</aside>
https://embed.notionlytics.com/wt/ZXlKd1lXZGxTV1FpT2lKalpUUXdaalZpWW1KaU5UazBPRFl6T0RsbFltRmlORFppT1dObFpETXhPQ0lzSW5kdmNtdHpjR0ZqWlZSeVlXTnJaWEpKWkNJNklrbGpiM1pzV2pOcU1VUnBRM1ZUUm1WNFRtdHlJbjA9
Large applications written in OOP are logically split into classes. To manage dependencies between classes, Magento 2 uses dependency injection during the class initialization. The dependency injection container (also known as object manager) is controlling the class object initialization process. Let's take a deeper dive into all capabilities of this entity.
An Object is an individual instance of a class. We define a class once and then produce objects out of it. Objects are also known as instances of a class.
An Object Manager is a set of high-level tools that are used by Magento to help instantiate objects. An object manager is capable of class dependency lookup and automatic resolution. You are not required to write import
or require
statements ever again.
An object manager is responsible for:
The process of automatic constructor argument resolution is called dependency injection. Here is how it looks in practice:
<?php
declare(strict_types=1);
use Magento\\Store\\Model\\StoreManagerInterface;
use Magento\\Catalog\\Api\\Data\\ProductInterfaceFactory;
use Magento\\Catalog\\Model\\ResourceModel\\Eav\\Attribute;
class ExampleClass
{
protected $storeManager;
protected $productFactory;
protected $attribute;
public function __construct(
// a dependencies to inject
StoreManagerInterface $storeManager, // interface
ProductInterfaceFactory $productFactory, // generated factory
Attribute $attribute // class
) {
$this->productFactory = $productFactory;
$this->storeManager = $storeManager;
$this->attribute = $attribute;
}
}