Event driven application

Post on 22-Nov-2014

2,631 views 0 download

description

Event driven development in PHP applications are becoming more prevalent. This presentation goes over the origins of the concept from the Observer pattern, details the benefits and drawbacks, and discusses real world application of the pattern.

transcript

Event DrivenApplicationsWrangle Cross-Cutting

Concerns

Chris SaylorLead Engineer

@cjsaylor

150+ countries14 million weekly classparticipants15 million monthly pageviews47 million monthly servicerequests

Zumba Fitness

What to expectWhat are cross-cutting concerns?Origins from Observer patternAsynchronous vs SynchronousLogic abstractionDemoEvents in the wildAdvantages and drawbacksFuther considerations

What are cross-cuttingconcerns?

Cross-cutting concerns are parts of a program thatrely on or must affect many other parts of the

system.Source: Wikipedia.org

Examples of cross-cutting concernsLoggingCachingProduct feature interactionMonitoringRecord audit trailState Management

What are the risks of cross cuttingconcerns?

Coupling systems too tightly (aka "Tangling")Lots of code duplications (aka "Scattering")

Single Responsibility PrincipleIf a class and its services should be responsible forone thing, how do we deal with unrelated business

rules that must be addressed by that class?

Origins from Observer pattern

Observer PatternThe root of Event Driven Applications began with the observerpattern which tracks the state of a subject by attaching observers tothe subject so that when it changes, all observers are notified.

SplObserverThe interface is a standard lib to implement thispattern.

SplObserver

An SplSubject object attaches the observer.The SplSubject then calls an update on the observer when notifyingthe registered observers.

Asynchronous vs Synchronous

App event in javascriptSyncronous in order of executionAsyncronous in order of completion

$('p') .on('click', function() { (function() { console.log('first?'); }()); }) .on('click', function() { (function() { console.log('second?'); }()); });

App event in PHPSyncronousPredictable order of execution and completion

<?php $event ->on('event1', function() { echo "First!"; }) ->on('event1', function() { echo "Second." });

Logic abstraction

Separation of Concerns

Use synchronous events to separate chunks of business logic awayfrom core functionality

Provides for modularityAllow for unit testing listenersMultiple messages - multiple listeners

Example Before<?php function login($username, $password) { try { // get user from db $user = Repository::get($username, $password); // Check if an admin if ($user->role->admin) { $_SESSION['admin'] = true; } // Log user's login $user->updateLastLogin(time()); Repository::saveUser($user); } catch (\Exception $e) { return false; } return true;}

Example After<?php function login($username, $password) { try { // get user from db $user = Repository::get($username, $password); // Fire post login event $event::trigger('afterLogin', compact('user')); } catch (\Exception $e) { return false; } return true;

<?php $event::listen('afterLogin', function($event) { if ($event->data['user']->role->admin) { $_SESSION['admin'] = true } }); $event::listen('afterLogin', function($event) { $event->data['user']->updateLastLogin(time()); Repository::saveUser($event->data['user']); });

Demohttps://github.com/cjsaylor/event-driven-apps-demo

Branch: cart-demo (cart-demo-event)

Events in the wild

CakePHPControllers have beforeFilter, beforeRender, and components withsimilar callbacksModels have behaviors with before find/saveExposed event library

Symfony 2 can be used as a standalone event library.

Can be easily incorporated via ComposerEventDispatcher

Zend can be used to create events and listeners of said

eventsCan be extracted from Zend, but not as easily as Symfony 2.

EventManagers

Many others...GuzzleMagentoLithium

Advantages and Drawbacks

Decouple CodeAdvantage:

Modular design can reduce core functionality bugs when modifyingmodules.Allows for open frameworks to allow third parties to implementcustom solutions without modifying core files.

Disadvantage:

Code is harder to follow and needs good organizationalmanagement.Documentation of what events will be called when is almost amust.

Plugin ArchitectureAdvantage:

Enable or disable plugins on the fly.Essential for open source targeting developers to implement.

Disadvantage:

No dependencies should exist be between plugins.

TestingAdvantage:

Test the listeners separate from the core functionality.Execute listeners from core test cases via external event triggers.Mock event callbacks to test event trigger placement.

Disadvantage:

Multiple event bindings in test suites results in undesired eventtriggers.Unbinding specific event callbacks can be difficult to do.

Further considerations

Synchronous orAsynchronous?

Make a judgment on whether an event listener should process it nowor post-request process with a call to a message queue.

Events and Variable ReferenceUsing an object for passage into the event so all event handlers have

access to the same data.

SpecializationIs the logic I'm trying to abstract into an event worth doing so? Would

this logic best be housed in the core logic?

Thank youGet this presentation on slideshare:

http://www.slideshare.com/cjsaylor/event-driven-application