SimpleMagento - Magento tutorials, tips and discussions with simplicity in mind
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk
SimpleMagento - Magento tutorials, tips and discussions with simplicity in mind
No Result
View All Result
Home Magento 2

Basics of dependency injection and its usage in Magento 2 – Sample 1

by freelancer
April 19, 2022
0 0
Share on FacebookShare on Twitter

One of a very powerful changes in Magento 2 is the usage of dependency injection design pattern. With this pattern, quite quite a bit has been modified inside codebase, and many new points have been launched. In this article, I’ll try to elucidate the very fundamentals of this design pattern, and its implementation in Magento 2 to help these which might be newcomers in the field of dependency injection.

Let me first start by explaining the basic thought behind this design pattern. By following dependency injection, it’s best to ask for required belongings when your object is being created, instead of creating belongings after they’re required. This will allow class isolation and unbiased development, in addition to unit testing ensuing from ease of mocking required objects. Before continuing, let me show you an example:

class A
{
  ...
  public function read()
  
  ...
}

Previous example demonstrates straightforward class A with method read(). In this method, we require database connection object which is created in the first line of method. This is one factor most of you is likely to be used to, and it is one factor associated to what’s used in Magento 1.x (with usage of factory pattern). The subsequent example will implement the an identical logic, nevertheless following dependency injection pattern:

class A
{
  protected $_dbh;
  ...
  public function __construct(DatabaseConnection $connection)
  {
    $this->_dbh = $connection;
  }
  ...
  public function read()
  
    $this->_dbh->question('SELECT ...');
    ...
  
  ...
}

In this example, database connection object has been handed to class A by approach of constructor, instead of being created inside read() method. Even though this simply is not the one method of passing dependencies onto object, this implementation is used in Magento 2. So, what exactly have we achieved by this?

For starters, class A is likely to be developed independently of class DatabaseConnection as we are going to on a regular basis fake connection for purpose of development. It is unbiased of DatabaseConnection implementation, and it is quite a bit easier to examine our code this method.

One of the downsides you have probably noticed is that the second snippet of the code is greater than the sooner one. And that is true, for an example MagentoCatalogModelProduct has constructor that spreads all through 52 lines of code. Also, in the occasion you try to debug this code, you will uncover it is a truly troublesome exercise. Luckily, this is the place testing comes in hand.

For initialization of such large objects, dependency injection introduces dependency injection container, and in Magento 2 it is often called ObjectManager. This container is responsible for resolving and creating dependencies upon object creation. Let’s have a look at how this works on a straightforward example:

class A
{
  public function __construct(B $b)
  {
    $this->_b = $b;
  }
}

When creating object from class A, the subsequent would happen:

  1. ObjectManager->create(‘A’) is named
  2. Constructor of A is examined
  3. Class B is being created, and used for creating A

In these few steps, ObjectManager has created an object from class. But for the second, let’s not maintain it that straightforward, and take into consideration we have now now a quantity of implementations of class B. This raises the question, which implementation is likely to be used? And the reply to that question is likely to be found in one of the di.xml files, which might be located in the subsequent locations:

  • {moduleDir}/etc/{areaCode}/di.xml
  • {moduleDir}/etc/di.xml
  • app/etc/di/*.xml

Within these files, you can discover/specify these settings:

Class definitions: Type and amount of dependencies. Fortunately, Magento 2 makes use of constructor signature to compile this routinely.
Instance configuration: Definition on the fitting solution to instantiate objects. This contains setting of types and digitalTypes which might be out of scope of this article.
Abstraction-implementation mappings: These mappings assist you choose most popular interface implementation. This is one factor similar to rewrite in Magento 1.x.

One different factor that is left proper right here to elucidate is type of objects that are being injected. In Magento 2, they’re separated into two groups: injectable, and non-injectable. Let me first start by explaining what non-injectable objects are. After that, injectables is likely to be self-explanatory.

For an example, let’s have a look at the product page, the place you need to show a gift product, and some related products. If you move product model to your controller, first you will have to call load on that product to get the current product. But as quickly as that object is used, the place will you get data about totally different merchandise? So you is likely to be guessing that product model is one of the non-injectable objects. Actually, all objects which have some selection of id, may very well be non-injectables: merchandise, orders, cart objects, clients, …

In order to make use of non-injectable objects in your code, you have to request their factory. For example, in case you’re making an try and load a quantity of merchandise, your code will depend on product factory, and by approach of that object you’d call create() method with id of the merchandise you are trying to load. Proxies are primarily used for lazy loading of elective or expensive dependencies.

In order to have points a bit additional sophisticated, usually you truly need to depend on non-injectable object itself, as they behave like singletons. Good example for this may very well be a CMS page.

To sum up, we have now now covered the very fundamentals of dependency injection design pattern. There is far more to cover, nevertheless I hope that I managed to rush up this course of for you. There are many provides on this subject available on the market, nevertheless in case you’re in the Magento specifics, place to start may very well be the official documentation.

In case you feel you need some extra help, we are going to offer you a detailed custom report based on our technical audit – be at liberty to get in contact and see what we are going to do for you!

Tags: ProgrammingMagento 2
Previous Post

MageMeter – a new way to present and share Magento performance benchmarks

Next Post

Magento 2 frontend architecture – Sample 1

freelancer

freelancer

Related Posts

Magento 2

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Magento 2

Implementing payment gateway in Magento 2 Spinned – Sample 1

April 22, 2022
Magento 2 Payment

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Magento 2

Routing in Magento 2 – Sample 1

April 22, 2022
MVC Magento 2

Magento 2 Controllers – Sample 1

April 22, 2022
Magento 2

How to create a basic module in Magento 2 – Sample 1

April 22, 2022

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Administration
  • Search
  • Configuration
  • Starting Up
  • Extensions
  • News
  • PWA
  • Magento 2 API
  • Programming
  • MVC Magento 2
  • UX/UI Design
  • Shipping Magento 2
  • Database
  • Magento 2 Payment
  • Magento 2
  • Cache
  • Frontend
  • Integration
  • Dev Talk
  • Life at Inchoo
  • Checkout
  • Tips
  • UI components
  • Products
  • Online Marketing
  • Debugging
  • Magento
  • Search Magento 2
  • Upgrading Magento 2
  • Marketing
  • eCommerce Talk
  • Events & Observers
  • Uncategorized

Popular Post

Magento 2

Magento 2 frontend architecture – Sample 1

April 22, 2022
UX/UI Design

Magento 2 Luma Theme Under The Scope

March 27, 2022
Magento 2 Payment

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Magento 2

Moving the validation error message, this time globally

March 25, 2022
No Result
View All Result
[vc_row full_width="stretch_row" vc_row_background="" css=".vc_custom_1516082354216{margin-top: 30px !important;padding-top: 22px !important;padding-bottom: 22px !important;}"][vc_column el_class=".footer_center" offset="vc_col-lg-offset-3 vc_col-lg-6"]
[vc_empty_space height="15px"][vc_column_text css=".vc_custom_1516083863519{margin-bottom: 0px !important;}" el_class=".copyright"]Copyright © 2018 JNews. Photography Blog theme by Jegtheme.[/vc_column_text][/vc_column][/vc_row]
No Result
View All Result
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk

© 2023 JNews - Premium WordPress news & magazine theme by Jegtheme.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In