SlideShare a Scribd company logo
A Series of Fortunate Events 
Matthias Noback 
Twitter: @matthiasnoback
What are events, really? 
Things that happen
They trigger actions
Just now... 
Attendees arrived, 
triggered me to turn on microphone, 
which triggered you to stop talking, 
which triggered me to start talking
Events in software 
Events model what happened in a system
Other parts of the system 
can respond to what happened
Imperative programming 
Only commands 
doThis(); 
doThat(); 
updateSomething($something); 
return $something;
Extracting events 
doThis(); 
// this was done 
doThat(); 
// that was done 
updateSomething($something) 
// something was updated 
return $something;
Starting position 
class PostService 
{ 
... 
function addComment($postId, $comment) 
{ 
$post = $this->fetchPost($postId); 
$post->addComment($comment); 
$this->save($post); 
$this->logger->info('New comment'); 
$this->mailer->send('New comment'); 
} 
}
Starting position 
class PostService 
{ 
function __construct( 
Mailer $mailer, 
Logger $logger 
) { 
$this->mailer = $mailer; 
$this->logger = $logger; 
} 
function addComment($postId, $comment) 
{ 
... 
} 
}
Making events explicit 
class PostService 
{ 
function addComment($postId, $comment) 
{ 
... 
$this->newCommentAdded(); 
} 
function newCommentAdded() 
{ 
$this->logger->info('New comment'); 
$this->mailer->send('New comment'); 
} 
}
Dependency graph 
PPoossttSSeerrvviiccee 
Logger 
Mailer
Design issues (1) 
I don't think the PostService should 
know how to use a Mailer and a Logger
Design issues (2) 
I want to change the behavior of 
PostService without modifying the 
class itself
Fix the problems 
By introducing events! 
(later)
Observer pattern 
Notify other parts of the application 
when a change occurs 
class PostService 
{ 
function newCommentAdded() 
{ 
foreach ($this->observers as $observer) { 
$observer->notify(); 
} 
} 
}
Observer contract 
Subject knows nothing about its 
observers, except their very simple 
interface 
interface Observer 
{ 
function notify(); 
}
Concrete observers 
class LoggingObserver implements Observer 
{ 
function __construct(Logger $logger) 
{ 
$this->logger = $logger; 
} 
function notify() 
{ 
$this->logger->info('New comment'); 
} 
}
Concrete observers 
class NotificationMailObserver implements Observer 
{ 
function __construct(Mailer $mailer) 
{ 
$this->mailer = $mailer; 
} 
function notify() 
{ 
$this->mailer->send('New comment'); 
} 
}
Configuration 
class PostService 
{ 
function __construct(array $observers) 
{ 
$this->observers = $observers; 
} 
} 
$postService = new PostService( 
array( 
new LoggingObserver($logger), 
new NotificationMailObserver($mailer) 
) 
);
Before 
PPoossttSSeerrvviiccee 
Logger 
Mailer
After 
NotificationMailObserver 
Observer 
Observer 
LoggingObserver 
Logger 
Mailer 
PostService
Design Principles Party
Single responsibility 
Each class has one small, 
well-defined responsibility
Single responsibility 
● PostService: 
“add comments to posts” 
● LoggingObserver: 
“write a line to the log” 
● NotificationMailObserver: 
“send a notification mail”
Single responsibility 
When a change is required, it can be 
isolated to just a small part of the 
application
Single responsibility 
● “Capitalize the comment!”: 
PostService 
● “Use a different logger!”: 
LoggerObserver 
● “Add a timestamp to the notification mail!”: 
NotificationMailObserver
Dependency inversion 
Depend on abstractions, not on 
concretions
Dependency inversion 
First PostService depended on 
something concrete: the Mailer, the 
Logger.
PostService Logger 
Mailer
Dependency inversion 
Now it depends on something abstract: 
an Observer
PostService 
Observer 
Observer
Dependency inversion 
Only the concrete observers depend on 
concrete things like Mailer and Logger
LoggingObserver 
NotificationMailObserver 
Logger 
Mailer
Open/closed 
A class should be open for extension and 
closed for modification
Open/closed 
You don't need to modify the class to 
change its behavior
PostService 
Observer 
Observer Observer
Open/closed 
We made it closed for modification, 
open for extension
Event data 
Mr. Boddy was murdered! 
● By Mrs. Peacock 
● In the dining room 
● With a candle stick
Currently missing! 
class LogNewCommentObserver implements Observer 
{ 
function notify() 
{ 
// we'd like to be more specific 
$this->logger->info('New comment'); 
} 
}
Event object 
class CommentAddedEvent 
{ 
public function __construct($postId, $comment) 
{ 
$this->postId = $postId; 
$this->comment = $comment; 
} 
function comment() 
{ 
return $this->comment; 
} 
function postId() 
{ 
return $this->postId; 
} 
}
Event object 
We use the event object 
to store the context of the event
From observer... 
interface Observer 
{ 
function notify(); 
}
… to event handler 
interface CommentAddedEventHandler 
{ 
function handle(CommentAddedEvent $event); 
}
Event handlers 
class LoggingEventHandler implements 
CommentAddedEventHandler 
{ 
function __construct(Logger $logger) 
{ 
$this->logger = $logger; 
} 
public function handle(CommentAddedEvent $event) 
{ 
$this->logger->info( 
'New comment' . $event->comment() 
); 
} 
}
Event handlers 
class NotificationMailEventHandler implements 
CommentAddedEventHandler 
{ 
function __construct(Mailer $mailer) 
{ 
$this->mailer = $mailer; 
} 
public function handle(CommentAddedEvent $event) 
{ 
$this->mailer->send( 
'New comment: ' . $event->comment(); 
); 
} 
}
Configuration 
class PostService 
{ 
function __construct(array $eventHandlers) 
{ 
$this->eventHandlers = $eventHandlers; 
} 
} 
$postService = new PostService( 
array( 
new LoggingEventHandler($logger), 
new NotificationMailEventHandler($mailer) 
) 
);
Looping over event handlers 
class PostService 
{ 
public function addComment($postId, $comment) 
{ 
$this->newCommentAdded($postId, $comment); 
} 
function newCommentAdded($postId, $comment) 
{ 
$event = new CommentAddedEvent( 
$postId, 
$comment 
); 
foreach ($this->eventHandlers as $eventHandler) { 
$eventHandler->handle($event); 
} 
} 
}
Introducing a Mediator 
Instead of talking to the event handlers 
Let's leave the talking to a mediator
Mediators for events 
● Doctrine, Zend: Event manager 
● The PHP League: Event emitter 
● Symfony: Event dispatcher
Before 
PostService 
LoggingEventHandler::handle() 
NotificationMailEventHandler::handle()
After 
PostService EventDispatcher 
LoggingEventHandler::handle() 
NotificationMailEventHandler::handle()
In code 
class PostService 
{ 
function __construct(EventDispatcherInterface $dispatcher) 
{ 
$this->dispatcher = $dispatcher; 
} 
function newCommentAdded($postId, $comment) 
{ 
$event = new CommentAddedEvent($postId, $comment); 
$this->dispatcher->dispatch( 
'comment_added', 
$event 
); 
} 
}
Event class 
Custom event classes should extend 
Symfony Event class: 
use SymfonyComponentEventDispatcherEvent; 
class CommentAddedEvent extends Event 
{ 
... 
}
Configuration 
use SymfonyComponentEventDispatcherEvent; 
$dispatcher = new EventDispatcher(); 
$loggingEventHandler = new 
LoggingEventHandler($logger); 
$dispatcher->addListener( 
'comment_added', 
array($loggingEventHandler, 'handle') 
); 
... 
$postService = new PostService($dispatcher);
Symfony2 
● An event dispatcher is available as the 
event_dispatcher service 
● You can register event listeners using 
service tags
Inject the event dispatcher 
# services.yml 
services: 
post_service: 
class: PostService 
arguments: [@event_dispatcher]
Register your listeners 
# services.yml 
services: 
... 
logging_event_handler: 
class: LoggingEventHandler 
arguments: [@logger] 
tags: 
- { 
name: kernel.event_listener 
event: comment_added 
method: handle 
}
Events and application flow 
Symfony2 uses events to generate 
response for any given HTTP request
The HttpKernel 
$request = Request::createFromGlobals(); 
// $kernel is in an instance of HttpKernelInterface 
$response = $kernel->handle($request); 
$response->send();
Kernel events
kernel.request 
● Route matching 
● Authentication
kernel.controller 
● Replace the controller 
● Do some access checks
kernel.view 
● Render a template
kernel.response 
● Modify the response 
● E.g. inject the Symfony toolbar
kernel.exception 
● Generate a response 
● Render a nice page with the stack trace
Special types of events 
● Kernel events are not merely 
notifications 
● They allow other parts of the 
application to step in and modify or 
override behavior
Chain of responsibility 
Some sort 
of request 
Handler 1 Handler 2 Handler 3 
Some sort 
of request 
Some sort 
of request 
Response
Symfony example 
I've got an exception! 
What should I tell the user? 
Listener 1 Listener 2 Listener 3 
Exception! Exception! 
Response
Propagation 
class HandleExceptionListener 
{ 
function onKernelException( 
GetResponseForExceptionEvent $event 
) { 
$event->setResponse(new Response('Error!')); 
// this is the best response ever, don't let 
// other spoil it! 
$event->stopPropagation(); 
} 
}
Priorities 
$dispatcher = new EventDispatcher(); 
$dispatcher->addListener( 
'comment_added', 
array($object, $method), 
// priority 
100 
);
Concerns
Concern 1: Hard to understand 
“Click-through understanding” impossible 
$event = new CommentAddedEvent($postId, $comment); 
$this->dispatcher->dispatch( 
'comment_added', 
$event 
);
interface EventDispatcherInterface 
{ 
function dispatch($eventName, Event $event = null); 
... 
}
Solution 
Use Xdebug
Concern 2: Out-of-domain concepts 
● “Comment” 
● “PostId” 
● “Add comment to post” 
● “Dispatcher” (?!)
We did a good thing 
We fixed coupling issues
But this guy, Coupling, 
has a sister 
She's called Cohesion
Cohesion 
● Belonging together 
● Concepts like “dispatcher”, “event listener”, even 
“event”, don't belong in your code
Solutions (1) 
Descriptive, explicit naming: 
● NotificationMailEventListener becomes 
SendNotificationMailWhenCommentAdded 
● CommentAddedEvent becomes CommentAdded 
● onCommentAdded becomes 
whenCommentAdded
Solutions (1) 
This also hides implementation details!
Solutions (2) 
Use an event dispatcher for things 
that are not naturally cohesive anyway
Solutions (2) 
Use something else 
when an event dispatcher causes low cohesion
Example: resolving the controller 
$event = new GetResponseEvent($request); 
$dispatcher->dispatch('kernel.request', $event); 
$controller = $request->attributes->get('_controller'); 
$controller = $controllerResolver->resolve($request);
Concern 3: Loss of control 
● You rely on event listeners to do some really 
important work 
● How do you know if they are in place 
and do their job?
Solution 
● “Won't fix” 
● You have to learn to live with it
It's good
exercise 
control 
Inversion of control 
give up 
control!
Just like... 
● A router determines the right controller 
● The service container injects the right 
constructor arguments 
● And when you die, someone will bury your 
body for you
I admit, inversion of control can be scary
But it will 
● lead to better design 
● require less change 
● make maintenance easier
PresentationFinished 
AskQuestionsWhenPresentationFinished 
SayThankYouWhenNoMoreQuestions
Symfony, service definitions, kernel events 
http://leanpub.com/a-year-with-symfony/c/symfony-camp 
Pay even less ;)
Class and package design principles 
http://leanpub.com/principles-of-php-package-design/c/symfony-camp 
Get a $10 discount!
Design patterns 
● Observer 
● Mediator 
● Chain of responsibility 
● ... 
Design Patterns by “The Gang of Four”
SOLID principles 
● Single responsibility 
● Open/closed 
● Dependency inversion 
● ... 
Agile Software Development by Robert C. Martin
Images 
● www.ohiseered.com/2011_11_01_archive.html 
● Mrs. Peacock, Candlestick: 
www.cluecult.com 
● Leonardo DiCaprio: 
screenrant.com/leonardo-dicaprio-defends-wolf-wall-street-controversy/ 
● Book covers: 
Amazon 
● Party: 
todesignoffsite.com/events-2/to-do-closing-party-with-love-design/ 
● Russell Crowe: 
malinaelena.wordpress.com/2014/04/18/top-8-filme-cu-russell-crowe/
What did you think? 
joind.in/12541 
Twitter: @matthiasnoback

More Related Content

What's hot

2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern
Robert Pankowecki
 
Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)
Samuel ROZE
 
Symfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsSymfony World - Symfony components and design patterns
Symfony World - Symfony components and design patterns
Łukasz Chruściel
 
Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machine
Łukasz Chruściel
 
Symfony Events
Symfony EventsSymfony Events
Symfony Events
Brent Shaffer
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Ete programs
Ete programsEte programs
Ete programs
Mayur Wankhede
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmKotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Fabio Collini
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
Payal Dungarwal
 
The next step, part 2
The next step, part 2The next step, part 2
The next step, part 2
Pat Cavit
 
Event handling63
Event handling63Event handling63
Event handling63
myrajendra
 
The combine triad
The combine triadThe combine triad
The combine triad
Donny Wals
 
Managing parallelism using coroutines
Managing parallelism using coroutinesManaging parallelism using coroutines
Managing parallelism using coroutines
Fabio Collini
 
C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
Ananda Kumar HN
 
Resultados
ResultadosResultados
Resultados
jbersosa
 

What's hot (20)

2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern
 
Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)
 
Symfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsSymfony World - Symfony components and design patterns
Symfony World - Symfony components and design patterns
 
Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machine
 
Symfony Events
Symfony EventsSymfony Events
Symfony Events
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Ete programs
Ete programsEte programs
Ete programs
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmKotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere Stockholm
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
The next step, part 2
The next step, part 2The next step, part 2
The next step, part 2
 
Event handling63
Event handling63Event handling63
Event handling63
 
The combine triad
The combine triadThe combine triad
The combine triad
 
Managing parallelism using coroutines
Managing parallelism using coroutinesManaging parallelism using coroutines
Managing parallelism using coroutines
 
C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
 
Resultados
ResultadosResultados
Resultados
 

Similar to A Series of Fortunate Events - Symfony Camp Sweden 2014

A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015
Matthias Noback
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
Samuel ROZE
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
Konstantin Kudryashov
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
Marcello Duarte
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
Samuel ROZE
 
CQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationCQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony application
Samuel ROZE
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8
katbailey
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
Jakub Zalas
 
[4developers] The saga pattern v3- Robert Pankowiecki
[4developers] The saga pattern v3- Robert Pankowiecki[4developers] The saga pattern v3- Robert Pankowiecki
[4developers] The saga pattern v3- Robert Pankowiecki
PROIDEA
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
Kris Wallsmith
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
Kacper Gunia
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
Lars Jankowfsky
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
Nataliya Patsovska
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
Kris Wallsmith
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
wajrcs
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
Kacper Gunia
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 

Similar to A Series of Fortunate Events - Symfony Camp Sweden 2014 (20)

A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 
CQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationCQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony application
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
[4developers] The saga pattern v3- Robert Pankowiecki
[4developers] The saga pattern v3- Robert Pankowiecki[4developers] The saga pattern v3- Robert Pankowiecki
[4developers] The saga pattern v3- Robert Pankowiecki
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 

More from Matthias Noback

Rector fireside chat - PHPMiNDS meetup
Rector fireside chat - PHPMiNDS meetupRector fireside chat - PHPMiNDS meetup
Rector fireside chat - PHPMiNDS meetup
Matthias Noback
 
Service abstractions - Part 1: Queries
Service abstractions - Part 1: QueriesService abstractions - Part 1: Queries
Service abstractions - Part 1: Queries
Matthias Noback
 
Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019
Matthias Noback
 
Advanced web application architecture - PHP Barcelona
Advanced web application architecture  - PHP BarcelonaAdvanced web application architecture  - PHP Barcelona
Advanced web application architecture - PHP Barcelona
Matthias Noback
 
A testing strategy for hexagonal applications
A testing strategy for hexagonal applicationsA testing strategy for hexagonal applications
A testing strategy for hexagonal applications
Matthias Noback
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
Matthias Noback
 
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
Matthias Noback
 
Layers, ports and adapters
Layers, ports and adaptersLayers, ports and adapters
Layers, ports and adapters
Matthias Noback
 
Beyond design principles and patterns (muCon 2019 edition)
Beyond design principles and patterns (muCon 2019 edition)Beyond design principles and patterns (muCon 2019 edition)
Beyond design principles and patterns (muCon 2019 edition)
Matthias Noback
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
Advanced web application architecture Way2Web
Advanced web application architecture Way2WebAdvanced web application architecture Way2Web
Advanced web application architecture Way2Web
Matthias Noback
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
Beyond Design Principles and Patterns
Beyond Design Principles and PatternsBeyond Design Principles and Patterns
Beyond Design Principles and Patterns
Matthias Noback
 
Building Autonomous Services
Building Autonomous ServicesBuilding Autonomous Services
Building Autonomous Services
Matthias Noback
 
Advanced Application Architecture Symfony Live Berlin 2018
Advanced Application Architecture Symfony Live Berlin 2018Advanced Application Architecture Symfony Live Berlin 2018
Advanced Application Architecture Symfony Live Berlin 2018
Matthias Noback
 
Designing for Autonomy
Designing for AutonomyDesigning for Autonomy
Designing for Autonomy
Matthias Noback
 
Docker workshop
Docker workshopDocker workshop
Docker workshop
Matthias Noback
 
Docker swarm workshop
Docker swarm workshopDocker swarm workshop
Docker swarm workshop
Matthias Noback
 
Docker compose workshop
Docker compose workshopDocker compose workshop
Docker compose workshop
Matthias Noback
 
Building autonomous services
Building autonomous servicesBuilding autonomous services
Building autonomous services
Matthias Noback
 

More from Matthias Noback (20)

Rector fireside chat - PHPMiNDS meetup
Rector fireside chat - PHPMiNDS meetupRector fireside chat - PHPMiNDS meetup
Rector fireside chat - PHPMiNDS meetup
 
Service abstractions - Part 1: Queries
Service abstractions - Part 1: QueriesService abstractions - Part 1: Queries
Service abstractions - Part 1: Queries
 
Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019
 
Advanced web application architecture - PHP Barcelona
Advanced web application architecture  - PHP BarcelonaAdvanced web application architecture  - PHP Barcelona
Advanced web application architecture - PHP Barcelona
 
A testing strategy for hexagonal applications
A testing strategy for hexagonal applicationsA testing strategy for hexagonal applications
A testing strategy for hexagonal applications
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
 
Layers, ports and adapters
Layers, ports and adaptersLayers, ports and adapters
Layers, ports and adapters
 
Beyond design principles and patterns (muCon 2019 edition)
Beyond design principles and patterns (muCon 2019 edition)Beyond design principles and patterns (muCon 2019 edition)
Beyond design principles and patterns (muCon 2019 edition)
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
 
Advanced web application architecture Way2Web
Advanced web application architecture Way2WebAdvanced web application architecture Way2Web
Advanced web application architecture Way2Web
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
 
Beyond Design Principles and Patterns
Beyond Design Principles and PatternsBeyond Design Principles and Patterns
Beyond Design Principles and Patterns
 
Building Autonomous Services
Building Autonomous ServicesBuilding Autonomous Services
Building Autonomous Services
 
Advanced Application Architecture Symfony Live Berlin 2018
Advanced Application Architecture Symfony Live Berlin 2018Advanced Application Architecture Symfony Live Berlin 2018
Advanced Application Architecture Symfony Live Berlin 2018
 
Designing for Autonomy
Designing for AutonomyDesigning for Autonomy
Designing for Autonomy
 
Docker workshop
Docker workshopDocker workshop
Docker workshop
 
Docker swarm workshop
Docker swarm workshopDocker swarm workshop
Docker swarm workshop
 
Docker compose workshop
Docker compose workshopDocker compose workshop
Docker compose workshop
 
Building autonomous services
Building autonomous servicesBuilding autonomous services
Building autonomous services
 

Recently uploaded

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 

Recently uploaded (20)

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 

A Series of Fortunate Events - Symfony Camp Sweden 2014

  • 1. A Series of Fortunate Events Matthias Noback Twitter: @matthiasnoback
  • 2. What are events, really? Things that happen
  • 4. Just now... Attendees arrived, triggered me to turn on microphone, which triggered you to stop talking, which triggered me to start talking
  • 5. Events in software Events model what happened in a system
  • 6. Other parts of the system can respond to what happened
  • 7. Imperative programming Only commands doThis(); doThat(); updateSomething($something); return $something;
  • 8. Extracting events doThis(); // this was done doThat(); // that was done updateSomething($something) // something was updated return $something;
  • 9. Starting position class PostService { ... function addComment($postId, $comment) { $post = $this->fetchPost($postId); $post->addComment($comment); $this->save($post); $this->logger->info('New comment'); $this->mailer->send('New comment'); } }
  • 10. Starting position class PostService { function __construct( Mailer $mailer, Logger $logger ) { $this->mailer = $mailer; $this->logger = $logger; } function addComment($postId, $comment) { ... } }
  • 11. Making events explicit class PostService { function addComment($postId, $comment) { ... $this->newCommentAdded(); } function newCommentAdded() { $this->logger->info('New comment'); $this->mailer->send('New comment'); } }
  • 13. Design issues (1) I don't think the PostService should know how to use a Mailer and a Logger
  • 14. Design issues (2) I want to change the behavior of PostService without modifying the class itself
  • 15. Fix the problems By introducing events! (later)
  • 16. Observer pattern Notify other parts of the application when a change occurs class PostService { function newCommentAdded() { foreach ($this->observers as $observer) { $observer->notify(); } } }
  • 17. Observer contract Subject knows nothing about its observers, except their very simple interface interface Observer { function notify(); }
  • 18. Concrete observers class LoggingObserver implements Observer { function __construct(Logger $logger) { $this->logger = $logger; } function notify() { $this->logger->info('New comment'); } }
  • 19. Concrete observers class NotificationMailObserver implements Observer { function __construct(Mailer $mailer) { $this->mailer = $mailer; } function notify() { $this->mailer->send('New comment'); } }
  • 20. Configuration class PostService { function __construct(array $observers) { $this->observers = $observers; } } $postService = new PostService( array( new LoggingObserver($logger), new NotificationMailObserver($mailer) ) );
  • 22. After NotificationMailObserver Observer Observer LoggingObserver Logger Mailer PostService
  • 24. Single responsibility Each class has one small, well-defined responsibility
  • 25. Single responsibility ● PostService: “add comments to posts” ● LoggingObserver: “write a line to the log” ● NotificationMailObserver: “send a notification mail”
  • 26. Single responsibility When a change is required, it can be isolated to just a small part of the application
  • 27. Single responsibility ● “Capitalize the comment!”: PostService ● “Use a different logger!”: LoggerObserver ● “Add a timestamp to the notification mail!”: NotificationMailObserver
  • 28. Dependency inversion Depend on abstractions, not on concretions
  • 29. Dependency inversion First PostService depended on something concrete: the Mailer, the Logger.
  • 31. Dependency inversion Now it depends on something abstract: an Observer
  • 33. Dependency inversion Only the concrete observers depend on concrete things like Mailer and Logger
  • 35. Open/closed A class should be open for extension and closed for modification
  • 36. Open/closed You don't need to modify the class to change its behavior
  • 38. Open/closed We made it closed for modification, open for extension
  • 39. Event data Mr. Boddy was murdered! ● By Mrs. Peacock ● In the dining room ● With a candle stick
  • 40. Currently missing! class LogNewCommentObserver implements Observer { function notify() { // we'd like to be more specific $this->logger->info('New comment'); } }
  • 41. Event object class CommentAddedEvent { public function __construct($postId, $comment) { $this->postId = $postId; $this->comment = $comment; } function comment() { return $this->comment; } function postId() { return $this->postId; } }
  • 42. Event object We use the event object to store the context of the event
  • 43. From observer... interface Observer { function notify(); }
  • 44. … to event handler interface CommentAddedEventHandler { function handle(CommentAddedEvent $event); }
  • 45. Event handlers class LoggingEventHandler implements CommentAddedEventHandler { function __construct(Logger $logger) { $this->logger = $logger; } public function handle(CommentAddedEvent $event) { $this->logger->info( 'New comment' . $event->comment() ); } }
  • 46. Event handlers class NotificationMailEventHandler implements CommentAddedEventHandler { function __construct(Mailer $mailer) { $this->mailer = $mailer; } public function handle(CommentAddedEvent $event) { $this->mailer->send( 'New comment: ' . $event->comment(); ); } }
  • 47. Configuration class PostService { function __construct(array $eventHandlers) { $this->eventHandlers = $eventHandlers; } } $postService = new PostService( array( new LoggingEventHandler($logger), new NotificationMailEventHandler($mailer) ) );
  • 48. Looping over event handlers class PostService { public function addComment($postId, $comment) { $this->newCommentAdded($postId, $comment); } function newCommentAdded($postId, $comment) { $event = new CommentAddedEvent( $postId, $comment ); foreach ($this->eventHandlers as $eventHandler) { $eventHandler->handle($event); } } }
  • 49. Introducing a Mediator Instead of talking to the event handlers Let's leave the talking to a mediator
  • 50. Mediators for events ● Doctrine, Zend: Event manager ● The PHP League: Event emitter ● Symfony: Event dispatcher
  • 51. Before PostService LoggingEventHandler::handle() NotificationMailEventHandler::handle()
  • 52. After PostService EventDispatcher LoggingEventHandler::handle() NotificationMailEventHandler::handle()
  • 53. In code class PostService { function __construct(EventDispatcherInterface $dispatcher) { $this->dispatcher = $dispatcher; } function newCommentAdded($postId, $comment) { $event = new CommentAddedEvent($postId, $comment); $this->dispatcher->dispatch( 'comment_added', $event ); } }
  • 54. Event class Custom event classes should extend Symfony Event class: use SymfonyComponentEventDispatcherEvent; class CommentAddedEvent extends Event { ... }
  • 55. Configuration use SymfonyComponentEventDispatcherEvent; $dispatcher = new EventDispatcher(); $loggingEventHandler = new LoggingEventHandler($logger); $dispatcher->addListener( 'comment_added', array($loggingEventHandler, 'handle') ); ... $postService = new PostService($dispatcher);
  • 56. Symfony2 ● An event dispatcher is available as the event_dispatcher service ● You can register event listeners using service tags
  • 57. Inject the event dispatcher # services.yml services: post_service: class: PostService arguments: [@event_dispatcher]
  • 58. Register your listeners # services.yml services: ... logging_event_handler: class: LoggingEventHandler arguments: [@logger] tags: - { name: kernel.event_listener event: comment_added method: handle }
  • 59. Events and application flow Symfony2 uses events to generate response for any given HTTP request
  • 60. The HttpKernel $request = Request::createFromGlobals(); // $kernel is in an instance of HttpKernelInterface $response = $kernel->handle($request); $response->send();
  • 62. kernel.request ● Route matching ● Authentication
  • 63. kernel.controller ● Replace the controller ● Do some access checks
  • 65. kernel.response ● Modify the response ● E.g. inject the Symfony toolbar
  • 66. kernel.exception ● Generate a response ● Render a nice page with the stack trace
  • 67. Special types of events ● Kernel events are not merely notifications ● They allow other parts of the application to step in and modify or override behavior
  • 68. Chain of responsibility Some sort of request Handler 1 Handler 2 Handler 3 Some sort of request Some sort of request Response
  • 69. Symfony example I've got an exception! What should I tell the user? Listener 1 Listener 2 Listener 3 Exception! Exception! Response
  • 70. Propagation class HandleExceptionListener { function onKernelException( GetResponseForExceptionEvent $event ) { $event->setResponse(new Response('Error!')); // this is the best response ever, don't let // other spoil it! $event->stopPropagation(); } }
  • 71. Priorities $dispatcher = new EventDispatcher(); $dispatcher->addListener( 'comment_added', array($object, $method), // priority 100 );
  • 73. Concern 1: Hard to understand “Click-through understanding” impossible $event = new CommentAddedEvent($postId, $comment); $this->dispatcher->dispatch( 'comment_added', $event );
  • 74. interface EventDispatcherInterface { function dispatch($eventName, Event $event = null); ... }
  • 76. Concern 2: Out-of-domain concepts ● “Comment” ● “PostId” ● “Add comment to post” ● “Dispatcher” (?!)
  • 77. We did a good thing We fixed coupling issues
  • 78. But this guy, Coupling, has a sister She's called Cohesion
  • 79. Cohesion ● Belonging together ● Concepts like “dispatcher”, “event listener”, even “event”, don't belong in your code
  • 80. Solutions (1) Descriptive, explicit naming: ● NotificationMailEventListener becomes SendNotificationMailWhenCommentAdded ● CommentAddedEvent becomes CommentAdded ● onCommentAdded becomes whenCommentAdded
  • 81. Solutions (1) This also hides implementation details!
  • 82. Solutions (2) Use an event dispatcher for things that are not naturally cohesive anyway
  • 83. Solutions (2) Use something else when an event dispatcher causes low cohesion
  • 84. Example: resolving the controller $event = new GetResponseEvent($request); $dispatcher->dispatch('kernel.request', $event); $controller = $request->attributes->get('_controller'); $controller = $controllerResolver->resolve($request);
  • 85. Concern 3: Loss of control ● You rely on event listeners to do some really important work ● How do you know if they are in place and do their job?
  • 86. Solution ● “Won't fix” ● You have to learn to live with it
  • 88. exercise control Inversion of control give up control!
  • 89. Just like... ● A router determines the right controller ● The service container injects the right constructor arguments ● And when you die, someone will bury your body for you
  • 90. I admit, inversion of control can be scary
  • 91. But it will ● lead to better design ● require less change ● make maintenance easier
  • 93. Symfony, service definitions, kernel events http://leanpub.com/a-year-with-symfony/c/symfony-camp Pay even less ;)
  • 94. Class and package design principles http://leanpub.com/principles-of-php-package-design/c/symfony-camp Get a $10 discount!
  • 95. Design patterns ● Observer ● Mediator ● Chain of responsibility ● ... Design Patterns by “The Gang of Four”
  • 96. SOLID principles ● Single responsibility ● Open/closed ● Dependency inversion ● ... Agile Software Development by Robert C. Martin
  • 97. Images ● www.ohiseered.com/2011_11_01_archive.html ● Mrs. Peacock, Candlestick: www.cluecult.com ● Leonardo DiCaprio: screenrant.com/leonardo-dicaprio-defends-wolf-wall-street-controversy/ ● Book covers: Amazon ● Party: todesignoffsite.com/events-2/to-do-closing-party-with-love-design/ ● Russell Crowe: malinaelena.wordpress.com/2014/04/18/top-8-filme-cu-russell-crowe/
  • 98. What did you think? joind.in/12541 Twitter: @matthiasnoback