Application 2018-06-05

DI and Service Locator

Implement dependency injection patterns. Compare DI and Service Locator with constructor injection examples for loosely coupled code.

Read in: ja
DI and Service Locator

Overview

Summarizing the differences between DI and Service Locator

What is DI

Implementing the DI Pattern

Let's implement the DI pattern (Constructor Injection). Note that the DI pattern includes methods other than constructor injection, such as setter injection and method injection. For comparison, both non-DI and DI patterns will be implemented.

Non-DI Pattern

<?php
class SlackNotification
{
    public function notify(string $message)
    {
        echo $message;

        return $this;
    }
}

class Application
{
    protected $message;

    public function __construct()
    {
        $this->notification = new SlackNotification();
    }

    public function alert(string $message)
    {
        $this->notification->notify($message);
    }
}

// client
$application = new Application();
$application->alert('slack alert');

DI Pattern

<?php

interface NotificationInterface
{
    public function notify(string $message);
}

class SlackNotification implements NotificationInterface
{
    public function notify(string $message)
    {
        echo $message;

        return $this;
    }
}

class Application
{
    protected $message;

    public function __construct(NotificationInterface $notification) // DI
    {
        $this->notification = $notification;
    }

    public function alert(string $message)
    {
        $this->notification->notify($message);
    }
}

// client
$slackNotification = new SlackNotification();
$application = new Application($slackNotification); // DI
$application->alert('slack alert!');

Application does not hold the responsibility of SlackNotification, and only depends on NotificationInterface. Application is structured to accept (depend on) SlackNotification in the constructor.

The dependency injection part can be mocked, making it easier to test.

// For test
$mockNotification = new MockNotification(); // MockNotification implementing NotificationInterface
$application = new Application($mockNotification);
$application->alert('mock alert!');

Advantages and Disadvantages of DI

Advantages

Disadvantages

DI Container

What is a Service Locator

Something like this

<?php

class Application
{
    public function __construct($container)
    {
        $this->slackNotification = $container['slack.notification'];
    }
}

$application = new Applicaion($container);

References

Tags: DI Service Locator Design Pattern
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles