Reader small image

You're reading from  Mastering PHP 7

Product typeBook
Published inJun 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781785882814
Edition1st Edition
Languages
Right arrow
Author (1)
Branko Ajzele
Branko Ajzele
author image
Branko Ajzele

Branko Ajzele is a respected and highly accomplished software developer, book author, solution specialist, consultant, and team leader. He currently works for Interactive Web Solutions Ltd (iWeb), where he holds the role of senior developer and is the director of iWeb's Croatia office. Branko holds several respected IT certifications, including Zend Certified PHP Engineer, Magento Certified Developer, Magento Certified Developer Plus, Magento Certified Solution Specialist, Magento 2 Certified Solution Specialist, Magento 2 Certified Professional Developer, to mention just a few. He was crowned the e-commerce Developer of the Year by the Digital Entrepreneur Awards in October 2014 for his excellent knowledge and expertise in e-commerce development.
Read more about Branko Ajzele

Right arrow

Chapter 13. Resolving Dependencies

Writing a loosely coupled code has become an essential skill for any professional developer. While legacy applications had a tendency to pack it all up, thus ending in one big solid block of code, modern applications take a more gradient approach as they largely rely on third-party libraries and other components. Nowadays, hardly anyone builds their own mailer, logger, router, template engine, and so on. Great deal of these components are out there, waiting to be consumed by our application through Composer. As individual components themselves are tested and maintained by various community or commercial entities, the cost of maintaining our application is significantly reduced. The overall code quality itself improves as an indirect consequence of more specialized developers addressing specific functionalities that otherwise might fall out of the area of our expertise. Harmony that has been made possible via loosely coupled code.

There are a multitude of...

Mitigating the common problem


The dependency injection is a well-established software technique that deals with the problem of object dependencies, allowing us to write loosely coupled classes. While the pattern itself has been around for quite some time, the PHP ecosystem hasn't really picked it up until major frameworks such as Symfony started implementing it. Nowadays, it is a de facto standard for anything other than trivial types of application. The whole dependency problem is easily observed through a simple example:

<?php

class Customer
{
    protected $name;

    public function loadByEmail($email)
    {
        $mysqli = new mysqli('127.0.0.1', 'foggy', 'h4P9niq5', 'sakila');

        $statement = $mysqli->prepare('SELECT * FROM customer WHERE email = ?');
        $statement->bind_param('s', $email);
        $statement->execute();

        $customer = $statement->get_result()->fetch_object();

        $this->name = $customer->first_name . ' ' . $customer...

Understanding dependency injection


Throughout the introductory section, we touched upon passing dependency through the class __construct() method. There is more to it than just passing the dependent object. Let's consider the following three seemingly similar but different examples.

Though PHP has been supporting type hinting for quite a while now, it isn't uncommon to come across pieces of code, which are as follows:

<?php

class App
{
    protected $config;
    protected $logger;

    public function __construct($config, $logger)
    {
        $this->config = $config;
        $this->logger = $logger;
    }

    public function run()
    {
        $this->config->setValue('executed_at', time());
        $this->logger->log('executed');
    }
}

class Config
{
    protected $config = [];

    public function setValue($path, $value)
    {
        // implementation
    }
}

class Logger
{
    public function log($message)
    {
        // implementation
    }
}

$config =...

Understanding dependency injection container


A dependency injection container is an object that knows how to auto-wire classes together. The auto-wire term implies both instantiating and properly configuring objects. This is by no means an easy task, which is why there are several libraries addressing this functionality.

The DependencyInjection component provided by the Symfony framework is a neat dependency injection container that can be easily installed by Composer. Moving forward, let's go ahead and create a di-container directory where we will execute these commands and set up our project:

composer require symfony/dependency-injection

The resulting output suggests we should install some additional packages:

We need to make sure we add the symfony/yaml and symfony/config packages by running the following console commands:

composer require symfony/yaml
composer require symfony/config

The symfony/yaml package installs the Symfony Yaml component. This component parses the YAML strings into PHP...

Summary


The dependency injection is a simple technique that allows us to escape from the shackles of tight coupling. Combined with interface type hints, we get a powerful technique to write loosely coupled code. This isolates and minimizes the impact of possible future application design changes as well as its defects. Nowadays, it is considered irresponsible to even write modular and large code base applications without embracing these simple techniques.

Moving forward, we will take a closer look at the state of the ecosystem around PHP packages, their creation, and distribution.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering PHP 7
Published in: Jun 2017Publisher: PacktISBN-13: 9781785882814
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.
undefined
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 $15.99/month. Cancel anytime

Author (1)

author image
Branko Ajzele

Branko Ajzele is a respected and highly accomplished software developer, book author, solution specialist, consultant, and team leader. He currently works for Interactive Web Solutions Ltd (iWeb), where he holds the role of senior developer and is the director of iWeb's Croatia office. Branko holds several respected IT certifications, including Zend Certified PHP Engineer, Magento Certified Developer, Magento Certified Developer Plus, Magento Certified Solution Specialist, Magento 2 Certified Solution Specialist, Magento 2 Certified Professional Developer, to mention just a few. He was crowned the e-commerce Developer of the Year by the Digital Entrepreneur Awards in October 2014 for his excellent knowledge and expertise in e-commerce development.
Read more about Branko Ajzele