Slide 1

Slide 1 text

IOC container @hannesvdvreken #phpuk18

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

IoC Container

Slide 13

Slide 13 text

IoC Container

Slide 14

Slide 14 text

WHAT IS IOC? IoC == Inversion of Control

Slide 15

Slide 15 text

But first: Design patterns WHAT IS IOC?

Slide 16

Slide 16 text

class Service { public function calculate() { // Get stuff from FTP. // 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. // 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 // Do calculations. // Return result. } } WHAT IS IOC?

Slide 19

Slide 19 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 20

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

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

Slide 22 text

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

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 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 27

Slide 27 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 28

Slide 28 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 29

Slide 29 text

FtpStorage Service depends on depends on Ftp WHAT IS IOC?

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 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 34

Slide 34 text

new Service($ftp); WHAT IS IOC?

Slide 35

Slide 35 text

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

Slide 36

Slide 36 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 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 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 40

Slide 40 text

No content

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

CONSTRUCTOR INJECTION namespace Psr\Container; interface ContainerInterface { public function get($id); public function has($id); }

Slide 44

Slide 44 text

Automatic object resolution

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

Constructor injection CONSTRUCTOR INJECTION

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

Reflection CONSTRUCTOR INJECTION

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

Recursively CONSTRUCTOR INJECTION

Slide 52

Slide 52 text

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

Slide 53

Slide 53 text

Helping the container

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

Solution: Aliasing. REGISTRATION - BINDING

Slide 56

Slide 56 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 57

Slide 57 text

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

Slide 58

Slide 58 text

Solution: Define dependencies. REGISTRATION - BINDING

Slide 59

Slide 59 text

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

Slide 60

Slide 60 text

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

Slide 61

Slide 61 text

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

Slide 62

Slide 62 text

Example: Global state in a - Translator - Entity Manager - Event dispatcher REGISTRATION - BINDING

Slide 63

Slide 63 text

Solution: Sharing an instance. REGISTRATION - BINDING

Slide 64

Slide 64 text

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

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

Solution: Contextual binding. REGISTRATION - BINDING

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

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

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

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

Slide 74

Slide 74 text

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

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

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

Slide 78

Slide 78 text

Also useful for: - Quickly injecting stuff 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

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

Slide 81

Slide 81 text

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

Slide 82

Slide 82 text

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

Slide 83

Slide 83 text

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

Slide 84

Slide 84 text

Where to put all this? REGISTRATION

Slide 85

Slide 85 text

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

Slide 86

Slide 86 text

Symfony: - Configuration files - Factories REGISTRATION

Slide 87

Slide 87 text

Using a container

Slide 88

Slide 88 text

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

Slide 89

Slide 89 text

Retrieving objects CALLING THE CONTAINER

Slide 90

Slide 90 text

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

Slide 91

Slide 91 text

Retrieving objects, with arguments CALLING THE CONTAINER

Slide 92

Slide 92 text

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

Slide 93

Slide 93 text

// League $container->add('fs.images', function () { return $container->get('fs', ['images']); }); CALLING THE CONTAINER

Slide 94

Slide 94 text

Calling functions, with resolved params CALLING THE CONTAINER

Slide 95

Slide 95 text

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

Slide 96

Slide 96 text

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

Slide 97

Slide 97 text

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

Slide 98

Slide 98 text

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

Slide 99

Slide 99 text

Tagging CALLING THE CONTAINER

Slide 100

Slide 100 text

Beware: Tagging in Symfony != Tagging in Laravel CALLING THE CONTAINER

Slide 101

Slide 101 text

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

Slide 102

Slide 102 text

Bonus

Slide 103

Slide 103 text

Solving circular dependencies BONUS - CIRCULAR DEPENDENCIES

Slide 104

Slide 104 text

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

Slide 105

Slide 105 text

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

Slide 106

Slide 106 text

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

Slide 107

Slide 107 text

recap: Reflection Aliasing Soft dependencies Using container

Slide 108

Slide 108 text

Thank you! @hannesvdvreken #phpuk18

Slide 109

Slide 109 text

Time for questions. @hannesvdvreken #phpuk18

Slide 110

Slide 110 text

No content

Slide 111

Slide 111 text

• https://getstream.io/try-the-api REFERENCES