Slide 1

Slide 1 text

IOC container beyond constructor injection @hannesvdvreken PHP Eindhoven

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

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

IoC Container

Slide 8

Slide 8 text

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

Slide 9

Slide 9 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 10

Slide 10 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 11

Slide 11 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 12

Slide 12 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 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

WHAT IS IOC? Give away control: Inversion of Control IoC container to the rescue

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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

Slide 21

Slide 21 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 22

Slide 22 text

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

Slide 23

Slide 23 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 24

Slide 24 text

WHAT IS IOC? Dependency injection: Injecting `Storage` into `Service` Dependency inversion: Interface + implementation Inversion of Control: The container builds our objects trough composition

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

Automatic constructor injection

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

CONSTRUCTOR INJECTION Constructor injection

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

CONSTRUCTOR INJECTION Reflection

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

CONSTRUCTOR INJECTION Recursively

Slide 34

Slide 34 text

Helping the container

Slide 35

Slide 35 text

REGISTRATION Service Providers

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

REGISTRATION Register bindings in the register method

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

REGISTRATION Bind a concretion for every interface

Slide 45

Slide 45 text

REGISTRATION Bind everything with its class name

Slide 46

Slide 46 text

REGISTRATION Unless you bind multiple versions

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

REGISTRATION - CONTEXTUAL BINDING Contextual binding

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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

Slide 51

Slide 51 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 52

Slide 52 text

Inflection REGISTRATION - CONTAINER EVENTS

Slide 53

Slide 53 text

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

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

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

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

REGISTRATION - CONTAINER EVENTS Method injection

Slide 59

Slide 59 text

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

Slide 60

Slide 60 text

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

Slide 61

Slide 61 text

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

Slide 62

Slide 62 text

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

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

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

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

REGISTRATION - TAGGING Tagging

Slide 69

Slide 69 text

$this->app->tag('fs.files', 'fs'); $this->app->tag('fs.photos', 'fs');

Slide 70

Slide 70 text

$this->app->tag( ['fs.photos', 'fs.files'], 'fs' );

Slide 71

Slide 71 text

$this->app->tag( 'fs.photos', ['fs', 'photos'] );

Slide 72

Slide 72 text

$this->app->tagged('fs');

Slide 73

Slide 73 text

Using the container

Slide 74

Slide 74 text

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

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

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

Slide 78

Slide 78 text

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

Slide 79

Slide 79 text

$this->app->tagged('fs');

Slide 80

Slide 80 text

Bonus

Slide 81

Slide 81 text

BONUS - SOFT DEPENDENCIES Solving circular dependencies

Slide 82

Slide 82 text

BONUS - CIRCULAR DEPENDENCIES Solving circular dependencies

Slide 83

Slide 83 text

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

Slide 84

Slide 84 text

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

Slide 85

Slide 85 text

BONUS - NOT SUPPORTED Not supported!

Slide 86

Slide 86 text

BONUS - NOT SUPPORTED Contextual binding for methods

Slide 87

Slide 87 text

BONUS - NOT SUPPORTED https:/ /github.com/laravel/ framework/pull/12183

Slide 88

Slide 88 text

BONUS - METHOD LEVEL CONTEXTUAL BINDING $this->app—>when('Foo@bar') ->needs(QueueContract::class) ->give('queue.redis');

Slide 89

Slide 89 text

BONUS - METHOD LEVEL CONTEXTUAL BINDING $this->app—>when('Foo@bar') takes precedence over $this->app—>when('Foo')

Slide 90

Slide 90 text

Reflection Binding Calling code Bonus

Slide 91

Slide 91 text

Thank you! https://joind.in/talk/xxxxx @hannesvdvreken PHP Eindhoven

Slide 92

Slide 92 text

Time for questions. @hannesvdvreken PHP Eindhoven

Slide 93

Slide 93 text

• http:/ /mwl.be REFERENCES