Slide 1

Slide 1 text

IOC container @hannesvdvreken Laracon EU 2016

Slide 2

Slide 2 text

Hi, my name is Hannes.

Slide 3

Slide 3 text

!

Slide 4

Slide 4 text

madewithlove.be !$%&'

Slide 5

Slide 5 text

IoC Container

Slide 6

Slide 6 text

I O C

Slide 7

Slide 7 text

International O C

Slide 8

Slide 8 text

International Olympic C

Slide 9

Slide 9 text

International Olympic Committee

Slide 10

Slide 10 text

International Olympic Committee

Slide 11

Slide 11 text

WHAT IS IOC? IoC == Inversion of Control

Slide 12

Slide 12 text

WHAT IS IOC? But first: Design patterns

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

WHAT IS IOC? 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. } }

Slide 15

Slide 15 text

WHAT IS IOC? 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. } }

Slide 16

Slide 16 text

WHAT IS IOC? 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. } }

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

WHAT IS IOC? class Service { public function __construct(FtpStorage $storage) {
 $this->storage = $storage; } }

Slide 19

Slide 19 text

WHAT IS IOC? interface Storage { public function get($key); }

Slide 20

Slide 20 text

WHAT IS IOC? \ class FtpStorage implements Storage { public function __construct(Ftp $ftp) { $this->ftp = $ftp; } public function get($key) { … } }

Slide 21

Slide 21 text

WHAT IS IOC? class Service { public function __construct(Storage $storage) {
 $this->storage = $storage; } }

Slide 22

Slide 22 text

WHAT IS IOC? new Service(new FtpStorage(new Ftp($settings)));

Slide 23

Slide 23 text

WHAT IS IOC? Don’t create these instances yourself

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

WHAT IS IOC? \ class FtpStorage implements Storage { public function __construct(Ftp $ftp) { $this->ftp = $ftp; } public function get($key) { // Get it and return it. } }

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

WHAT IS IOC? $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.

Slide 32

Slide 32 text

WHAT IS IOC? IoC container is here to help you with Composition

Slide 33

Slide 33 text

CONSTRUCTOR INJECTION illuminate/container league/container symfony/dependency-injection aura/di … container-interop/container-interop

Slide 34

Slide 34 text

Automatic constructor injection

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

CONSTRUCTOR INJECTION Constructor injection

Slide 37

Slide 37 text

$app->make(SendInvoice::class);

Slide 38

Slide 38 text

CONSTRUCTOR INJECTION Reflection

Slide 39

Slide 39 text

(new \ReflectionClass($class)) ->getConstructor() ->getParameters();

Slide 40

Slide 40 text

CONSTRUCTOR INJECTION Recursively

Slide 41

Slide 41 text

Helping the container

Slide 42

Slide 42 text

REGISTRATION Service Providers

Slide 43

Slide 43 text

class ServiceProvider { public function register() { … } public function boot(Dispatcher $events) }

Slide 44

Slide 44 text

class ServiceProvider { public function register() {…} public function boot(Dispatcher $events) { … } }

Slide 45

Slide 45 text

class ServiceProvider { protected $defer = true; public function register() {…} public function provides() { return [ Mailer::class, SwiftMailer::class, ]; } }

Slide 46

Slide 46 text

REGISTRATION Register bindings in the register method

Slide 47

Slide 47 text

REGISTRATION - BINDING $this->app->bind( MailerContract::class, SwiftMailer::class );

Slide 48

Slide 48 text

REGISTRATION - BINDING $this->app->bind(Mailer::class, function () { $mailer = new SwiftMailer(); return new LogDecorator($mailer); });

Slide 49

Slide 49 text

REGISTRATION - BINDING $this->app->singleton(Mailer::class, function () { … });

Slide 50

Slide 50 text

REGISTRATION - BINDING $this->app->alias( Mailer::class, 'mailer' );

Slide 51

Slide 51 text

REGISTRATION Bind a concretion for every interface

Slide 52

Slide 52 text

REGISTRATION Bind everything with its class name

Slide 53

Slide 53 text

REGISTRATION Unless you bind multiple versions

Slide 54

Slide 54 text

REGISTRATION $this->app->bind('fs.photos', function () {}); $this->app->bind('fs.files', function () {});

Slide 55

Slide 55 text

REGISTRATION - CONTEXTUAL BINDING Contextual binding

Slide 56

Slide 56 text

REGISTRATION - CONTEXTUAL BINDING $this->app ->when(PhotosController::class) ->needs(FilesystemInterface::class) ->give('fs.photos');

Slide 57

Slide 57 text

REGISTRATION - CONTEXTUAL BINDING No more DB::connection('db1')->table($table)->…;

Slide 58

Slide 58 text

$this->app->bind('db.1', function () { return $this->app['db'] ->connection('db1'); }); $this->app ->when(EventListener::class) ->needs(ConnectionInterface::class) ->give('db.1');

Slide 59

Slide 59 text

Inflection REGISTRATION - CONTAINER EVENTS

Slide 60

Slide 60 text

REGISTRATION - CONTAINER EVENTS Inflection (aka “container events”)

Slide 61

Slide 61 text

REGISTRATION - CONTAINER EVENTS $this->app->resolving( function (Foo $foo) {…} );

Slide 62

Slide 62 text

use App\Contracts\EnvironmentAware; $this->app->resolving( function (EnvironmentAware $object) { $object->setEnv( $this->app->environment() ); } );

Slide 63

Slide 63 text

interface EnvironmentAware { public function setEnv($env); }

Slide 64

Slide 64 text

trait EnvironmentAware { public function setEnv($env) { $this->env = $env; } private function isEnv($envs): bool { return in_array($this->env, (array) $envs); } }

Slide 65

Slide 65 text

REGISTRATION - CONTAINER EVENTS Method injection

Slide 66

Slide 66 text

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

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

$this->app->resolving(function (Mailer $mailer) { $mailer->setQueueResolver(function () { return $this->app->make(Queue::class); }); );

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

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

Slide 74

Slide 74 text

$this->app->resolving(function (Validator) { $fileTypes = $app['config']->get(…) $validator->setAllowedFileTypes($fileTypes); );

Slide 75

Slide 75 text

Using the container

Slide 76

Slide 76 text

CALLING THE CONTAINER Preferably only for - Factories - Event Dispatchers - Router - Command Bus

Slide 77

Slide 77 text

$this->app->make('fs'); $this->app->make('fs', […]); $this->app->bind( 'fs', function ($app, $args) {…} );

Slide 78

Slide 78 text

$this->app->call(function (Mailer $mailer) {}); $this->app->call([$listener, 'handle']); $this->app->call('Listener::handle'); $this->app->call('Listener@handle');

Slide 79

Slide 79 text

$func = $this->app->wrap('Listener@handle'); $func();

Slide 80

Slide 80 text

public function wrap($callback) { return function () { $this->call($callback); }; }

Slide 81

Slide 81 text

Bonus

Slide 82

Slide 82 text

BONUS - SOFT DEPENDENCIES Solving circular dependencies

Slide 83

Slide 83 text

BONUS - CIRCULAR DEPENDENCIES Solving circular dependencies

Slide 84

Slide 84 text

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

Slide 85

Slide 85 text

BONUS - CIRCULAR DEPENDENCIES $mailer = new Mailer(); $queue = new Queue(MailerInterface $mailer); $mailer->setQueueResolver(function () { return $this->app->make('queue'); });

Slide 86

Slide 86 text

BONUS - NOT SUPPORTED Contextual binding for methods (unsupported)

Slide 87

Slide 87 text

BONUS - METHOD LEVEL CONTEXTUAL BINDING $this->app—>when('FooController@store') ->needs(QueueContract::class) ->give('queue.redis'); https:/ /github.com/laravel/framework/pull/12183

Slide 88

Slide 88 text

recap: Reflection Binding Calling code Bonus

Slide 89

Slide 89 text

Thank you! https://joind.in/talk/xxxxx @hannesvdvreken Laracon EU 2016

Slide 90

Slide 90 text

Time for questions. @hannesvdvreken Laracon EU 2016

Slide 91

Slide 91 text

• http:/ /mwl.be REFERENCES