Upgrade to Pro — share decks privately, control downloads, hide ads and more …

IoC container - CODEid Odessa 2018

IoC container - CODEid Odessa 2018

Did you know your IoC container can do a whole lot more than just constructor injection? Besides that it is actually packed with features. Inflectors, resolving callbacks, aliasing, method invocation to name a few. In this talk you will learn how to leverage the power of a great container and service providers to write better, loosely coupled code. Well designed code put together by your IoC container will make your applications SOLID, modular, lean and decoupled from the framework!

Hannes Van De Vreken

December 08, 2018
Tweet

More Decks by Hannes Van De Vreken

Other Decks in Technology

Transcript

  1. IOC container
    @hannesvdvreken
    @laravelliveuk
    IOC container
    Hannes Van De Vreken

    View full-size slide

  2. Hi, my name is Hannes.

    View full-size slide

  3. IoC Container

    View full-size slide

  4. IoC Container

    View full-size slide

  5. International
    O
    C

    View full-size slide

  6. International
    Olympic
    C

    View full-size slide

  7. International
    Olympic
    Committee

    View full-size slide

  8. International
    Olympic
    Committee

    View full-size slide

  9. IoC Container

    View full-size slide

  10. IoC Container

    View full-size slide

  11. IoC Container

    View full-size slide

  12. WHAT IS IOC?
    IoC == Inversion of Control

    View full-size slide

  13. WHAT IS IOC?
    $service = new Service();
    $service->calculate();
    $service = $container->get(Service::class);
    $service->calculate();

    View full-size slide

  14. WHAT IS IOC?
    class Service
    {
    public function __construct()
    {
    init();
    }
    public function init()
    {
    $config = config(‘ftpsettings…’);
    $this->ftp = new FTP(…);
    }
    public function calculate() {…}
    }

    View full-size slide

  15. But first:
    Refresh your knowledge of
    Design patterns
    WHAT IS IOC?

    View full-size slide

  16. class Service
    {
    public function init()
    { // setup FTP
    }
    public function calculate()
    {
    // Get stuff from FTP.
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  17. class Service
    {
    public function __construct(Ftp $ftp)
    {
    }
    public function calculate()
    {
    // Get stuff from FTP.
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  18. class Service
    {
    public function __construct(Ftp $ftp)
    {
    }
    public function calculate()
    {
    // Get stuff from FTP.
    // Add caching to prevent hitting FTP over and over again
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  19. class Service
    {
    public function __construct(Ftp $ftp)
    {
    }
    public function calculate()
    {
    // Get stuff from FTP.
    // Add caching to prevent hitting FTP over and over again
    // Log that FTP is accessed.
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  20. class Service
    {
    public function __construct(Ftp $ftp)
    {
    }
    public function calculate()
    {
    // Get stuff from FTP.
    // Add caching to prevent hitting FTP over and over again
    // Log that FTP is accessed.
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  21. class FtpStorage
    {
    public function __construct(Ftp $ftp)
    {
    $this->ftp = $ftp;
    }
    public function get($filename)
    {
    // Get it.
    // Cache it.
    // Log it.
    // Return it.
    }
    }
    WHAT IS IOC?

    View full-size slide

  22. class Service
    {
    public function __construct(FtpStorage $storage)
    {

    $this->storage = $storage;
    }
    public function calculate()
    {
    $value = $this->storage->get($key);
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  23. interface Storage
    {
    public function get($filename);
    }
    WHAT IS IOC?

    View full-size slide

  24. class FtpStorage implements Storage
    {
    public function __construct(Ftp $ftp)
    {
    $this->ftp = $ftp;
    }
    public function get($filename)
    {

    }
    }
    WHAT IS IOC?

    View full-size slide

  25. class Service
    {
    public function __construct(FtpStorage $storage)
    {

    $this->storage = $storage;
    }
    public function calculate()
    {
    $value = $this->storage->get($key);
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  26. class Service
    {
    public function __construct(Storage $storage)
    {

    $this->storage = $storage;
    }
    public function calculate()
    {
    $value = $this->storage->get($key);
    // Do calculations.
    // Return result.
    }
    }
    WHAT IS IOC?

    View full-size slide

  27. class FtpStorage
    {
    public function __construct(Ftp $ftp)
    {
    $this->ftp = $ftp;
    }
    public function get($filename)
    {
    // Get it.
    // Cache it.
    // Log it.
    // Return it.
    }
    }
    WHAT IS IOC?

    View full-size slide

  28. class CacheDecorator implements Storage
    {
    public function __construct(Cache $cache, Storage $wrapped)
    {…}
    public function get($key)
    {
    return $this->cache->remember($key, 60, function () {
    return $this->wrapped->get($key);
    });
    }
    }
    WHAT IS IOC?

    View full-size slide

  29. class LogDecorator implements Storage
    {
    public function __construct(LoggerInterface $log, Storage $wrapped)
    {…}
    public function get($key)
    {
    $this->log->info('Retrieved value for '.$key);
    return $this->wrapped->get($key);
    }
    }
    WHAT IS IOC?

    View full-size slide

  30. class FtpStorage
    {
    public function __construct(Ftp $ftp)
    {
    $this->ftp = $ftp;
    }
    public function get($filename)
    {
    // Get it.
    // Cache it.
    // Log it.
    // Return it.
    }
    }
    WHAT IS IOC?

    View full-size slide

  31. class FtpStorage
    {
    public function __construct(Ftp $ftp)
    {
    $this->ftp = $ftp;
    }
    public function get($filename)
    {
    // Get it.
    // Return it.
    }
    }
    WHAT IS IOC?

    View full-size slide

  32. FtpStorage
    Service
    depends on
    depends on
    Ftp
    WHAT IS IOC?

    View full-size slide

  33. FtpStorage
    Service
    depends on
    Ftp
    WHAT IS IOC?
    implements
    Storage
    depends on

    View full-size slide

  34. Service
    WHAT IS IOC?
    implements
    Storage
    depends on
    FtpStorage CacheDecorator
    LogDecorator
    S3Storage

    View full-size slide

  35. WHAT IS IOC?
    FtpStorage
    implements
    Storage
    Service
    depends on
    depends on
    Ftp
    FtpStorage
    ervice
    depends on
    depends on
    Ftp

    View full-size slide

  36. $service = new Service();
    WHAT IS IOC?

    View full-size slide

  37. $service = new Service(
    new CacheDecorator(
    $cache,
    new LogDecorator(
    $logger,
    new FtpStorage(
    new Ftp($settings)
    )
    )
    )
    );
    WHAT IS IOC?

    View full-size slide

  38. $container->get(Service::class);
    1) Make FtpStorage
    2) Wrap it with LogDecorator
    3) Wrap LogDecorator instance with CacheDecorator
    4) New up Service with CacheDecorator instance.
    WHAT IS IOC?

    View full-size slide

  39. Dependency inversion:
    Interface + implementation
    Dependency injection:
    Injecting `Storage` into `Service`
    Inversion of Control:
    The container builds your objects and calls them
    WHAT IS IOC?

    View full-size slide

  40. Inversion of Control
    IoC container to the rescue
    WHAT IS IOC?

    View full-size slide

  41. Let the IoC container help
    you with Composition
    WHAT IS IOC?

    View full-size slide

  42. symfony/dependency-injection
    illuminate/container
    aura/di
    zendframework/zend-di
    pimple/pimple
    league/container
    bitexpert/disco

    container-interop/container-interop
    psr/container (PSR-11)
    CONSTRUCTOR INJECTION

    View full-size slide

  43. PSR-11
    namespace Psr\Container;
    interface ContainerInterface
    {
    public function get($id);
    public function has($id);
    }

    View full-size slide

  44. Automatic object resolution

    View full-size slide

  45. $listener = $container->get(SendInvoice::class);
    $listener->listen($event);
    CONSTRUCTOR INJECTION

    View full-size slide

  46. Reflection
    CONSTRUCTOR INJECTION

    View full-size slide

  47. class SendInvoice
    {
    public function __construct(Mailer $mailer)
    {
    $this->mailer = $mailer;
    }
    public function listen(InvoiceGeneratedEvent $event)
    {

    }
    }
    CONSTRUCTOR INJECTION

    View full-size slide

  48. Constructor injection
    CONSTRUCTOR INJECTION

    View full-size slide

  49. (new \ReflectionClass($classname))
    ->getConstructor()
    ->getParameters();
    CONSTRUCTOR INJECTION

    View full-size slide

  50. Recursively
    CONSTRUCTOR INJECTION

    View full-size slide

  51. CONSTRUCTOR INJECTION
    SendInvoice ➡ Mailer ➡ SMTP

    View full-size slide

  52. Auto wiring:
    - Laravel
    - Symfony
    - Zend
    - league/container
    - …
    CONSTRUCTOR INJECTION

    View full-size slide

  53. But what if our code depends on
    interfaces…
    The container can’t construct interfaces?
    CONSTRUCTOR INJECTION

    View full-size slide

  54. Helping the container

    View full-size slide

  55. Situation 1:
    When <> is type hinted,
    resolve <> instead
    REGISTRATION - BINDING

    View full-size slide

  56. Solution:
    Aliasing.
    REGISTRATION - BINDING

    View full-size slide

  57. // Laravel
    $container->alias(MailerInterface::class, Mailer::class);
    REGISTRATION - BINDING

    View full-size slide

  58. // Laravel
    $container->bind(MailerInterface::class, function () {
    return $container->get(Mailer::class);
    });
    REGISTRATION - BINDING

    View full-size slide

  59. // The PHP League
    $container->add(MailerInterface::class, Mailer::class);
    REGISTRATION - BINDING

    View full-size slide

  60. Situation 2:
    When <> has non-type hinted
    constructor arguments.
    REGISTRATION - BINDING

    View full-size slide

  61. class Mailer
    {
    /**
    * @param string $username
    * @param string $password
    */
    public function construct($username, $password)
    {…}
    }
    REGISTRATION - BINDING

    View full-size slide

  62. Solution:
    Define explicitly.
    REGISTRATION - BINDING

    View full-size slide

  63. // Laravel
    $container->bind(Mailer::class, function () {
    return new Mailer($username, $password);
    });
    REGISTRATION - BINDING

    View full-size slide

  64. // Symfony
    $container->register(Mailer::class)
    ->addArgument($username)
    ->addArgument($password);
    REGISTRATION - BINDING

    View full-size slide

  65. // The PHP League
    $container->add(Mailer::class)
    ->addArgument($username)
    ->addArgument($password);
    REGISTRATION - BINDING

    View full-size slide

  66. Situation 3:
    When <> is type hinted,
    always return the exact same object.
    REGISTRATION - BINDING

    View full-size slide

  67. Example:
    Global state in a
    - Translator (user’s locale)
    - Entity Manager
    - Event dispatcher
    REGISTRATION - BINDING

    View full-size slide

  68. Solution:
    Sharing an instance.
    REGISTRATION - BINDING

    View full-size slide

  69. // Laravel
    $container->singleton(EntityManagerInterface::class, function ()

    });
    $container->bind($key, $function, true);
    REGISTRATION - BINDING

    View full-size slide

  70. // Symfony
    $container->register(EntityManager::class)->setShared(false);
    REGISTRATION - BINDING

    View full-size slide

  71. // The PHP League
    $container->add(EntityManager::class)->setShared();
    $container->share(EntityManager::class);
    REGISTRATION - BINDING

    View full-size slide

  72. Situation 4:
    When different classes need a
    different object of the same
    interface.
    REGISTRATION - BINDING

    View full-size slide

  73. class PhotosController
    {
    public function __construct(FilesystemInterface $photos)
    {
    }
    }
    class FilesController
    {
    public function __construct(FilesystemInterface $files)
    {
    }
    }
    REGISTRATION - BINDING

    View full-size slide

  74. Solution:
    Contextual binding.
    REGISTRATION - BINDING

    View full-size slide

  75. // Laravel
    $container
    ->when(PhotosController::class)
    ->needs(FilesystemInterface::class)
    ->give(‘fs.photos');
    $container->bind('fs.photos', function () {});
    $container->bind('fs.files', function () {});
    REGISTRATION - CONTEXTUAL BINDING

    View full-size slide

  76. // Laravel
    $container->bind('fs.photos', …);
    $container->bind(PhotosController::class, function
    $fs = $container->get('fs.photos');
    return new PhotosController($fs);
    });
    REGISTRATION - BINDING

    View full-size slide

  77. // The PHP League
    $container->add('fs.photos', …);
    $container->add(PhotosController::class, function (
    $fs = $container->get('fs.photos');
    return new PhotosController($fs);
    });
    REGISTRATION - BINDING

    View full-size slide

  78. Situation 5:
    When resolving <>, do
    some setup.
    REGISTRATION - BINDING

    View full-size slide

  79. Example 1:
    When resolving the EntityManager,
    register some ModelListeners.
    REGISTRATION - BINDING

    View full-size slide

  80. Example 2:
    interface EnvironmentAware
    {
    public function setEnv($env);
    }
    trait EnvironmentAware
    {
    public function setEnv($env)
    {
    $this->env = $env;
    }
    }
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  81. Solution:
    Container events / inflection / hooks / …
    REGISTRATION - BINDING

    View full-size slide

  82. // Laravel
    $container->resolving(function (EnvironmentAware $object) {
    $object->setEnv(app()->environment());
    });
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  83. // The PHP League
    $container->inflector(EnvironmentAware::class)
    ->invokeMethod(‘setenv’, [app()->environment()]);
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  84. Also useful for:
    - Quickly injecting stuff
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  85. interface CommandBusAware
    trait CommandBusAware
    interface EventDispatcherAware
    trait EventDispatcherAware
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  86. Also useful for:
    - Quickly injecting stuff
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  87. Also useful for:
    - Quickly injecting stuff
    - Injecting soft dependencies
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  88. $container—>resolving(function (Mailer $mailer) {
    $mailer->setQueueResolver(function () {
    return $container->get(Queue::class);
    });
    );
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  89. Also useful for:
    - Quickly injecting stuff
    - Injecting soft dependencies
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  90. Also useful for:
    - Quickly injecting stuff
    - Injecting soft dependencies
    - Setting configurable values
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  91. $container->resolving(function (Validator $validator) {
    $fileTypes = $container->get('config')->get(…)
    $validator->setAllowedFileTypes($fileTypes);
    );
    REGISTRATION - CONTAINER EVENTS

    View full-size slide

  92. Where to put all this?
    REGISTRATION

    View full-size slide

  93. Service Providers!
    REGISTRATION

    View full-size slide

  94. REGISTRATION
    public function register()
    {
    // Bindings
    }
    public function boot()
    {
    // Macros, extensions, container events, …
    }

    View full-size slide

  95. REGISTRATION
    public function boot(View $view)
    {
    $view->composer(…);
    }

    View full-size slide

  96. REGISTRATION
    // The PHP League
    $container->addServiceProvider(AppServiceProvider::class);

    View full-size slide

  97. Using a container

    View full-size slide

  98. Retrieving objects
    CALLING THE CONTAINER

    View full-size slide

  99. // Psr\Container\ContainerInterface
    $container->has('fs');
    $container->get('fs');
    CALLING THE CONTAINER

    View full-size slide

  100. Retrieving objects, with arguments
    CALLING THE CONTAINER

    View full-size slide

  101. // Laravel
    $container->bind(‘fs', function ($args) {
    // Use $args[0] to see what folder to use.
    });
    $container->get('fs', [‘images’]);
    CALLING THE CONTAINER

    View full-size slide

  102. // Laravel
    $container->bind(‘fs', function ($args) {
    // Use $args[0] to see what folder to use.
    });
    $container->get('fs', [‘images']);
    $container->bind('fs.images', function () {
    return $container->get('fs', ['images']);
    CALLING THE CONTAINER

    View full-size slide

  103. Calling functions, with resolved params
    CALLING THE CONTAINER

    View full-size slide

  104. // Laravel
    $container->call($closure);
    $container->call(function (Mailer $mailer) {});
    $container->call([$listener, 'handle']);
    $container->call(‘Listener::handle’);
    CALLING THE CONTAINER

    View full-size slide

  105. // Laravel
    $container->call($closure);
    $container->call(function (Mailer $mailer) {});
    $container->call([$listener, 'handle']);
    $container->call(‘Listener::handle’);
    $container->call(‘Listener@handle');
    CALLING THE CONTAINER

    View full-size slide

  106. (new ReflectionFunction($callback))
    ->getParameters();
    CALLING THE CONTAINER

    View full-size slide

  107. // Laravel
    $func = $container->wrap('Listener@handle');
    $func();
    CALLING THE CONTAINER

    View full-size slide

  108. public function wrap($callback) {
    return function () {
    return $this->call($callback);
    };
    }
    CALLING THE CONTAINER

    View full-size slide

  109. Tagging
    CALLING THE CONTAINER

    View full-size slide

  110. // Laravel
    $container->tag('fs.images', 'filesystem');
    $container->tag('fs.pdfs', 'filesystem');
    $filesystems = $container->tagged('filesystem');
    foreach ($filesystems as $filesystem) {

    }
    CALLING THE CONTAINER

    View full-size slide

  111. // Laravel
    $container->tag(‘tool-1.dispatcher’, 'dispatcher');
    $container->tag(‘tool-2.dispatcher’, 'dispatcher');
    $dispatchers = $container->tagged(‘dispatcher');
    foreach ($dispatchers as $dispatcher) {
    $listener->delegate($dispatcher);
    }
    CALLING THE CONTAINER

    View full-size slide

  112. // The PHP League
    $container->add(‘fs.images’)->addTag(‘filesystems')
    $container->tag(‘fs.pdfs’)->addTag(‘filesystems');
    $filesystems = $container->get(‘filesystems');
    foreach ($filesystems as $filesystem) {

    }
    CALLING THE CONTAINER

    View full-size slide

  113. When to inject the container?

    View full-size slide

  114. Preferably only in
    - Event Dispatchers
    - Router
    - Command Bus
    - Factories
    - …
    CALLING THE CONTAINER

    View full-size slide

  115. Solving circular
    dependencies
    BONUS - CIRCULAR DEPENDENCIES

    View full-size slide

  116. $mailer = new Mailer(QueueInterface $queue);
    $queue = new Queue(MailerInterface $mailer);
    BONUS - CIRCULAR DEPENDENCIES

    View full-size slide

  117. $mailer = new Mailer();
    $queue = new Queue(MailerInterface $mailer);
    $mailer->setQueueResolver($callable);
    BONUS - CIRCULAR DEPENDENCIES

    View full-size slide

  118. // Laravel
    $queue = $container->get(QueueInterface::class);
    $container->resolving(function (Mailer $mailer) {
    $mailer->setQueueResolver(function () {
    return $container->get(QueueInterface::class);
    });
    });
    BONUS - CIRCULAR DEPENDENCIES

    View full-size slide

  119. Environment aware injection
    // Laravel
    $container->bind(‘fs.photos’, function () {
    if (getenv(‘APP_ENV’) === ‘integration’) {
    // Fill in memory adapter
    // with integration testing files

    } else {
    // Normal connection to S3.
    }
    });
    BONUS

    View full-size slide

  120. recap:
    Reflection
    Aliasing
    Soft dependencies
    Using container

    View full-size slide

  121. Thank you!
    @hannesvdvreken
    @laravelliveuk
    Thank you
    @hannesvdvreken

    View full-size slide

  122. Time for
    questions.
    @hannesvdvreken
    @laravelliveuk
    Time for questions
    @hannesvdvreken

    View full-size slide