Slide 1

Slide 1 text

IOC container @hannesvdvreken PHPCE

Slide 2

Slide 2 text

Hi, my name is Hannes.

Slide 3

Slide 3 text

!

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

IoC Container

Slide 7

Slide 7 text

I O C

Slide 8

Slide 8 text

International O C

Slide 9

Slide 9 text

International Olympic C

Slide 10

Slide 10 text

International Olympic Committee

Slide 11

Slide 11 text

International Olympic Committee

Slide 12

Slide 12 text

WHAT IS IOC? IoC == Inversion of Control

Slide 13

Slide 13 text

But first: Design patterns WHAT IS IOC?

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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?

Slide 17

Slide 17 text

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?

Slide 18

Slide 18 text

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?

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

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

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

FtpStorage Service depends on depends on Ftp WHAT IS IOC?

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

Don’t create these instances yourself WHAT IS IOC?

Slide 33

Slide 33 text

$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?

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

symfony/dependency-injection illuminate/container aura/di zendframework/zend-di pimple/pimple league/container … container-interop/container-interop psr/container (PSR-11) CONSTRUCTOR INJECTION

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

CONSTRUCTOR INJECTION namespace Interop\Container; use Psr\Container\ContainerInterface as PsrContainer; interface ContainerInterface extends PsrContainer { … }

Slide 39

Slide 39 text

Automatic object resolution

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

$listener = $container->get(SendInvoice::class); CONSTRUCTOR INJECTION

Slide 42

Slide 42 text

Constructor injection CONSTRUCTOR INJECTION

Slide 43

Slide 43 text

$listener = $container->get(SendInvoice::class); CONSTRUCTOR INJECTION

Slide 44

Slide 44 text

// League $container = new Container(); $container->delegate(new ReflectionContainer()); $listener = $container->get(SendInvoice::class); CONSTRUCTOR INJECTION

Slide 45

Slide 45 text

Reflection CONSTRUCTOR INJECTION

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

Recursively CONSTRUCTOR INJECTION

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

Helping the container

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

Solution: Aliasing. REGISTRATION - BINDING

Slide 53

Slide 53 text

// Symfony $container->setAlias(MailerInterface::class, Mailer::class); // Laravel $container->alias(MailerInterface::class, Mailer::class); // League, et al. $container->add(MailerInterface::class, function () { return $container->get(Mailer::class); }); REGISTRATION - BINDING

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

Solution: Define dependencies. REGISTRATION - BINDING

Slide 56

Slide 56 text

// Symfony $container->register(Mailer::class) ->addArgument(…); REGISTRATION - BINDING

Slide 57

Slide 57 text

// Pimple $container[MailerInterface::class] = function () { … }; REGISTRATION - BINDING

Slide 58

Slide 58 text

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

Slide 59

Slide 59 text

Example: Global state in a - Translator - View - Session REGISTRATION - BINDING

Slide 60

Slide 60 text

Solution: Sharing an instance. REGISTRATION - BINDING

Slide 61

Slide 61 text

// League $container->share(EntityManagerInterface::class, function () { … }); // Laravel $container->singleton(EntityManagerInterface::class, function () { … }); // Symfony $container->register()->setShared(true); REGISTRATION - BINDING

Slide 62

Slide 62 text

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

Slide 63

Slide 63 text

Solution: Contextual binding. REGISTRATION - BINDING

Slide 64

Slide 64 text

// Laravel $container->bind('fs.photos', function () {}); $container->bind('fs.files', function () {}); REGISTRATION - BINDING

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

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

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

// League $container->inflector(EntityManager, function ($em) $em->getConfiguration() ->getEntityListenerResolver() ->register(new ModelListener()); }); REGISTRATION - BINDING

Slide 70

Slide 70 text

// Laravel $container->resolving(function (EntityManager $em) … }); REGISTRATION - BINDING

Slide 71

Slide 71 text

interface EnvironmentAware { public function setEnv($env); } REGISTRATION - CONTAINER EVENTS

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

$container->resolving(function (EnvironmentAware $object) { $object->setEnv(getenv(‘APP_ENV’)); }); REGISTRATION - CONTAINER EVENTS

Slide 74

Slide 74 text

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

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

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

Slide 78

Slide 78 text

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

Slide 79

Slide 79 text

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

Slide 80

Slide 80 text

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

Slide 81

Slide 81 text

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

Slide 82

Slide 82 text

Where to put all this? REGISTRATION

Slide 83

Slide 83 text

container-interop/service-provider Similar to: - league/container - illuminate/container REGISTRATION

Slide 84

Slide 84 text

Symfony: - Configuration files - Factories REGISTRATION

Slide 85

Slide 85 text

Using a container

Slide 86

Slide 86 text

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

Slide 87

Slide 87 text

Retrieving objects CALLING THE CONTAINER

Slide 88

Slide 88 text

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

Slide 89

Slide 89 text

Retrieving objects, with arguments CALLING THE CONTAINER

Slide 90

Slide 90 text

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

Slide 91

Slide 91 text

// Laravel $container->bind('fs.images', function () { return $container->make('fs', ['images']); }); CALLING THE CONTAINER

Slide 92

Slide 92 text

Calling functions, with resolved params CALLING THE CONTAINER

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

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

Slide 95

Slide 95 text

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

Slide 96

Slide 96 text

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

Slide 97

Slide 97 text

Tagging CALLING THE CONTAINER

Slide 98

Slide 98 text

// Laravel $container->tag('fs.images', 'filesystem'); $container->tag('fs.pdfs', 'filesystem'); $filesystems = $container->tagged('filesystem'); foreach ($filesystems as $filesystem) { … } CALLING THE CONTAINER

Slide 99

Slide 99 text

Bonus

Slide 100

Slide 100 text

Solving circular dependencies BONUS - CIRCULAR DEPENDENCIES

Slide 101

Slide 101 text

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

Slide 102

Slide 102 text

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

Slide 103

Slide 103 text

$queue = $container->get(QueueInterface); // League $container->inflector(Mailer::class, function () { $mailer->setQueueResolver(function () use ($container) return $container->get(QueueInterface::class); }); }); BONUS CIRCULAR DEPENDENCIES

Slide 104

Slide 104 text

recap: Reflection Binding Calling code Bonus

Slide 105

Slide 105 text

@hannesvdvreken Thank you! PHPCE

Slide 106

Slide 106 text

@hannesvdvreken Time for questions. PHPCE

Slide 107

Slide 107 text

• http://mwl.be REFERENCES