Book Image

Magento 2 Cookbook

Book Image

Magento 2 Cookbook

Overview of this book

Magento 2 is an open source e-commerce platform that has all the functionality to function from small to large online stores. It is preferred by developers and merchants due to its new architecture, which makes it possible to extend the functionalities with plugins, a lot of which are now created by the community. This merchant and developer guide is packed with recipes that cover all aspects of Magento 2. The recipes start with simple how-to’s then delve into more advanced topics as the book progresses. We start with the basics of setting up a Magento 2 project on Apache or Nginx. Next, you will learn about basics including system tools and caching to get your Magento 2 system ready for the real work. We move on to simple tasks such as managing your store and catalog configuration. When you are familiar with this, we cover more complex features such as module and extension development. Then we will jump to the final part: advanced Magento 2 extensions. By the end of this book, you’ll be competent with all the development phases of Magento 2 and its most common elements.
Table of Contents (16 chapters)
Magento 2 Cookbook
Credits
Foreword
About the Authors
About the Reviewer
www.PacktPub.com
Preface
Index

Using dependency injection to pass classes to your own class


In Magento 2, they introduced the usage of dependency injection, which is a well-known design pattern that changes the way you use resources in the code. Using dependency injection, all the required resources are created when the class is instantiated instead of creating an object (through the Magento 1.x Mage class) when necessary. The benefit of this is that it is easier to use unit testing as it is possible to mock the required objects.

Getting ready

In this example, we will see how to create a new record in the demolist model created in the previous chapter. The record is created using an observer on the sales_order_place_after event that is dispatched after a new order is saved.

How to do it…

Follow these steps on how to use dependency injection:

  1. First, we declare the Observer to listen to the event that we want:

    etc/events.xml:

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento...