Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Magento 2 Developer's Guide

You're reading from   Magento 2 Developer's Guide Harness the power of Magento 2 to extend and customize your online store

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher Packt
ISBN-13 9781785886584
Length 412 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Toc

Table of Contents (14) Chapters Close

Preface 1. Understanding the Platform Architecture FREE CHAPTER 2. Managing the Environment 3. Programming Concepts and Conventions 4. Models and Collections 5. Using the Dependency Injection 6. Plugins 7. Backend Development 8. Frontend Development 9. The Web API 10. The Major Functional Areas 11. Testing 12. Building a Module from Scratch Index

Chapter 5. Using the Dependency Injection

Dependency injection is a software design pattern via which one or more dependencies are injected or passed by reference into an object. What this exactly means on a practical level is shown in the following two simple examples:

public function getTotalCustomers()
{
    $database = new \PDO( … );
    $statement = $database->query('SELECT …');
    return $statement->fetchColumn();
}

Here, you will see a simplified PHP example, where the $database object is created in the getTotalCustomers method. This means that the dependency on the database object is being locked in an object instance method. This makes for tight coupling, which has several disadvantages such as reduced reusability and a possible system-wide effect caused by changes made to some parts of the code.

A solution to this problem is to avoid methods with these sorts of dependencies by injecting a dependency into a method, as follows:

public function...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £16.99/month. Cancel anytime