Transcript
Page 1: Event driven application

Event DrivenApplicationsWrangle Cross-Cutting

Concerns

Page 2: Event driven application

Chris SaylorLead Engineer

@cjsaylor

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

Zumba Fitness

Page 3: Event driven application

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

Page 4: Event driven application

What are cross-cuttingconcerns?

Page 5: Event driven application

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

system.Source: Wikipedia.org

Page 6: Event driven application

Examples of cross-cutting concernsLoggingCachingProduct feature interactionMonitoringRecord audit trailState Management

Page 7: Event driven application

What are the risks of cross cuttingconcerns?

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

Page 8: Event driven application

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?

Page 9: Event driven application

Origins from Observer pattern

Page 10: Event driven application

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.

Page 11: Event driven application

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.

Page 12: Event driven application

Asynchronous vs Synchronous

Page 13: Event driven application

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?'); }()); });

Page 14: Event driven application

App event in PHPSyncronousPredictable order of execution and completion

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

Page 15: Event driven application

Logic abstraction

Page 16: Event driven application

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

Page 17: Event driven application

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;}

Page 18: Event driven application

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']); });

Page 19: Event driven application

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

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

Page 20: Event driven application

Events in the wild

Page 21: Event driven application

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

Page 22: Event driven application

Symfony 2 can be used as a standalone event library.

Can be easily incorporated via ComposerEventDispatcher

Page 23: Event driven application

Zend can be used to create events and listeners of said

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

EventManagers

Page 24: Event driven application

Many others...GuzzleMagentoLithium

Page 25: Event driven application

Advantages and Drawbacks

Page 26: Event driven application

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.

Page 27: Event driven application

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.

Page 28: Event driven application

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.

Page 29: Event driven application

Further considerations

Page 30: Event driven application

Synchronous orAsynchronous?

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

Page 31: Event driven application

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

access to the same data.

Page 32: Event driven application

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

this logic best be housed in the core logic?

Page 34: Event driven application

Thank youGet this presentation on slideshare:

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


Top Related