DIとサービスロケーター

DIとサービスロケーター

Read in: en
DIとサービスロケーター

概要

DIとService Locatorの違いについてまとめる

DIとは

DIパターンの実装

DIパターン(コンストラクタインジェクション)を実装してみる。 なお、DIパターンには、コンストラクタインジェクション、セッターインジェクション、メソッドインジェクションなどコンストラクタ以外からDIする方法もある。 比較のためにDIではないパターンとDIのパターンの両方を実装する。

DIではないパターン

<?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パターン

<?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!');

ApplicationSlackNotificationの責務を持たず、NotificationInterfaceのみに依存している。 ApplicationはコンスタラクタでSlackNotificationを受け入れる(依存する)形になっている。

依存注入部分はモック化できるのでテストしやすくなっている。

// For test
$mockNotification = new MockNotification(); // NotificationInterfaceを実装したMockNotification
$application = new Application($mockNotification);
$application->alert('mock alert!');

DIのメリットとデメリット

メリット

デメリット

DIコンテナ

サービスロケーターとは

こんな感じのやつ

<?php

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

$application = new Applicaion($container);

参考

Tags: DI サービスロケーター デザインパターン
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ サポート

このブログを応援していただける方は、以下からサポートをお願いします。いただいたサポートはブログ運営・技術研鑽に活用します。


関連記事