GlasgowPHP - May 2017
Scott Pringle
PHP Developer @ People's Postcode Lottery
DDDEdinburgh Organiser
An event is an action recognized by software, that may be handled by the software
https://en.wikipedia.org/wiki/Event_(computing)#Description
An Event is the encapsulation of a recorded action within an application
Me, probably plagiarising someone...
<?php
namespace Demo;
class UserRegistered
{
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function user(): User
{
return $this->user;
}
}
<?php
namespace Demo;
class UserRegisteredListener
{
private $emailer;
public function __construct(Emailer $emailer)
{
$this->emailer = $emailer;
}
public function onUserRegistered(UserRegistered $event)
{
$this->emailer->send(
$event->user()->email(),
'Subject',
'Message'
);
}
}
Mindset change from "will" to "has"
Thinking in reactions, not actions
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
/Users/robo/dev/php/Doctrine/doctrine-mapping.xsd">
<entity name="User">
<lifecycle-callbacks>
<lifecycle-callback type="prePersist" method="doStuffOnPrePersist"/>
<lifecycle-callback type="postPersist" method="doStuffOnPostPersist"/>
</lifecycle-callbacks>
</entity>
</doctrine-mapping>
<?php
namespace Demo;
class User
{
// All the properties
public function doStuffOnPrePersist()
{
$this->persisted = true;
}
public function doStuffOnPostPersist()
{
$this->persisted = false;
}
}
That I Can Agree With!
<?php
namespace Demo;
class UserRegisterController
{
private $eventDispatcher;
public function __construct(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
public function __invoke(Request $request)
{
$user = new User(...);
$this->eventDispatcher->dispatch(
'event.user_registered',
new UserRegistered(
$user
)
);
return new JsonResponse();
}
}
<!-- app/config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="app.event.user_registered" class="Demo\EventListener\UserRegistered">
<tag name="kernel.event_listener" event="event.user_registered" method="onUserRegistered" />
</service>
</services>
</container>
I've probably got that wrong...
Events can be handled asynchronously
Events should be immutable
Tell other parts of your application to do something
Create an audit trail...
Tell other applications to do something
Twitter: @Luciam91
http://slack.scotlandphp.co.uk