{"id":483,"date":"2013-01-16T00:30:58","date_gmt":"2013-01-15T23:30:58","guid":{"rendered":"http:\/\/codingexplained.com\/?p=483"},"modified":"2017-06-11T22:23:35","modified_gmt":"2017-06-11T20:23:35","slug":"zend-framework-2-event-manager","status":"publish","type":"post","link":"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager","title":{"rendered":"Zend Framework 2 Event Manager"},"content":{"rendered":"<p>In this article, we begin by introducing the high-level concepts of the event system that is a central part of Zend Framework 2. Afterwards, we will give you a simple example of attaching an event listener to an event and how to trigger an event.<\/p>\n<h3>The Event System<\/h3>\n<p>A fundamental principle is that Zend Framework 2 is based on the Event-driven Architecture (EDA). Simply put, the idea is that activities occur in response to events. Thus, activities are attached to events, and when a given event occurs, its attached activities are executed. This principle is well known in programming; Java and the .NET platform, for instance, both make heavy use of event handling.<\/p>\n<p>Imagine placing an order on Amazon. When the order is placed, a series of activities or processes should occur; a confirmation should be sent to the customer, the items should be picked from the warehouse, and the customer\u2019s credit card should be debited. These processes are registered on the OnOrderPlaced event, and when this event is triggered, the attached processes or activities are invoked.<\/p>\n<p>This approach gives a great deal of flexibility in a system. It is easy to add or remove activities that should happen when a given event occurs. Thus, business processes can easily be adapted to changing business needs.<\/p>\n<p>On the other hand, it can be hard to understand what actually happens during a business process. Activities can be attached to events almost anywhere in the application, and perhaps even added dynamically. This makes it difficult to both understand and debug a process; one must know which activities are attached to an event at runtime to understand exactly what happens. The flow of the business process is therefore less transparent than if it were implemented in a completely procedural fashion.<\/p>\n<p>A thing that further complicates this approach is the sequence in which activities are to be executed. Activities may depend upon each other; for instance, a customer\u2019s credit card should not be debited before the items are picked from the warehouse.<\/p>\n<p>The result of these disadvantages is that business processes are harder to understand, but it has been concluded by the Zend Framework team that the great extra flexibility outweighs this. As it turns out, the framework makes use of events internally, e.g. in the module manager.<\/p>\n<h3>The Event Manager<\/h3>\n<p>The event manager is mainly used to attach event listeners to events and to trigger events. It can be thought of as an implementation of the observer pattern where the event is the subject and the observers are the attached event listeners. An example of triggering events is given below.<\/p>\n<pre><code class=\"php\">use Zend\\EventManager\\EventManagerInterface;\r\nuse Zend\\EventManager\\EventManager;\r\nuse Zend\\EventManager\\EventManagerAwareInterface;\r\n\r\nclass UserMapper implements EventManagerAwareInterface {\r\n\tpublic function setEventManager(EventManagerInterface $events) {\r\n\t\t\/* ... *\/\r\n\t}\r\n\t\r\n\tpublic function getEventManager() {\r\n\t\t\/* ... *\/\r\n\t}\r\n\r\n\tpublic function register(User $user) {\r\n\t\t$this->getEventManager()->trigger(__function__ . '.pre', $this, array(\u2018user\u2019 => $user));\r\n\t\t\r\n\t\t\/\/ Register code here\r\n\t\t\r\n\t\t$this->getEventManager()->trigger(__function__ . '.post', $this, array(\u2018user\u2019 => $user));\r\n\t}\r\n}<\/code><\/pre>\n<p>The first argument passed to the <span class=\"code\">trigger()<\/span> method is the event name to trigger. In this example, events with the names <span class=\"code\">register.pre<\/span> and <span class=\"code\">register.post<\/span> are triggered. The second argument is the target, which will often be the class from which the event is triggered. The last argument is an array of data that will be passed to the event listener and can be used for various purposes such as logging.<\/p>\n<p>Attaching event listeners is a simple matter; an event listener is simply a PHP callback that takes an event object as its single parameter. This object enables developers to get information about the event that was triggered such as its name and any data passed with it.<\/p>\n<pre><code class=\"php\">use Zend\\EventManager\\EventManager;\r\nuse Zend\\EventManager\\EventInterface;\r\n\r\n$user_mapper = new UserMapper();\r\n$user_mapper->setEventManager(new EventManager());\r\n\r\n$user_mapper->getEventManager()->attach('register.post', function(EventInterface $event) {\r\n\t$logger = new \\Zend\\Log\\Logger();\r\n\t$logger->addWriter(new \\Zend\\Log\\Writer\\Stream('php:\/\/output'));\r\n\t\r\n\t$logger->log(\\Zend\\Log\\Logger::INFO, 'A user with the ID: ' . $event->getParam('user')->getUserID() . ' has registered');\r\n});<\/code><\/pre>\n<p>In the example above, an event listener is added to the <span class=\"code\">register.post<\/span> event. A callback function in the form of a closure or anonymous function is used. This function creates a log entry indicating that a user has registered and accesses the user object through the <span class=\"code\">getParam()<\/span> method. This method provides access to any parameters passed when the event was triggered. In this case, the User object that was passed in the previous example is accessed.<\/p>\n<p>A priority can also be specified when attaching an event listener to an event. The priority is simply an integer; the listener with the highest number is executed first.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article is meant as an introduction to Zend Framework 2&#8217;s event system. It begins by giving an introduction to the concepts of the event system and further discusses the event manager. Examples of how to attach event listeners and how to trigger events are also provided.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[38],"tags":[40,39,66],"series":[],"jetpack_publicize_connections":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Zend Framework 2 Event Manager<\/title>\n<meta name=\"description\" content=\"This article gives an overview of Zend Framework 2&#039;s event manager. Learn how to attach event listeners and trigger events with ZF2&#039;s event manager.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Zend Framework 2 Event Manager\" \/>\n<meta property=\"og:description\" content=\"This article gives an overview of Zend Framework 2&#039;s event manager. Learn how to attach event listeners and trigger events with ZF2&#039;s event manager.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager\" \/>\n<meta property=\"og:site_name\" content=\"Coding Explained\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/codingexplained\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/codingexplained\" \/>\n<meta property=\"article:published_time\" content=\"2013-01-15T23:30:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2017-06-11T20:23:35+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/codingexplained.com\/wp-content\/uploads\/2015\/11\/codingexplained-fb-promote.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"444\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Bo Andersen\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@codingexplained\" \/>\n<meta name=\"twitter:site\" content=\"@codingexplained\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Bo Andersen\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager\",\"url\":\"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager\",\"name\":\"Zend Framework 2 Event Manager\",\"isPartOf\":{\"@id\":\"https:\/\/codingexplained.com\/#website\"},\"datePublished\":\"2013-01-15T23:30:58+00:00\",\"dateModified\":\"2017-06-11T20:23:35+00:00\",\"author\":{\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d\"},\"description\":\"This article gives an overview of Zend Framework 2's event manager. Learn how to attach event listeners and trigger events with ZF2's event manager.\",\"breadcrumb\":{\"@id\":\"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/codingexplained.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Zend Framework 2 Event Manager\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/codingexplained.com\/#website\",\"url\":\"https:\/\/codingexplained.com\/\",\"name\":\"Coding Explained\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/codingexplained.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d\",\"name\":\"Bo Andersen\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g\",\"caption\":\"Bo Andersen\"},\"description\":\"I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!\",\"sameAs\":[\"https:\/\/codingexplained.com\",\"https:\/\/www.facebook.com\/codingexplained\",\"https:\/\/www.linkedin.com\/in\/ba0708\",\"https:\/\/twitter.com\/codingexplained\",\"https:\/\/www.youtube.com\/c\/codingexplained\"],\"url\":\"https:\/\/codingexplained.com\/author\/andy\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Zend Framework 2 Event Manager","description":"This article gives an overview of Zend Framework 2's event manager. Learn how to attach event listeners and trigger events with ZF2's event manager.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager","og_locale":"en_US","og_type":"article","og_title":"Zend Framework 2 Event Manager","og_description":"This article gives an overview of Zend Framework 2's event manager. Learn how to attach event listeners and trigger events with ZF2's event manager.","og_url":"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager","og_site_name":"Coding Explained","article_publisher":"https:\/\/www.facebook.com\/codingexplained","article_author":"https:\/\/www.facebook.com\/codingexplained","article_published_time":"2013-01-15T23:30:58+00:00","article_modified_time":"2017-06-11T20:23:35+00:00","og_image":[{"width":1200,"height":444,"url":"https:\/\/codingexplained.com\/wp-content\/uploads\/2015\/11\/codingexplained-fb-promote.png","type":"image\/png"}],"author":"Bo Andersen","twitter_card":"summary_large_image","twitter_creator":"@codingexplained","twitter_site":"@codingexplained","twitter_misc":{"Written by":"Bo Andersen","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager","url":"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager","name":"Zend Framework 2 Event Manager","isPartOf":{"@id":"https:\/\/codingexplained.com\/#website"},"datePublished":"2013-01-15T23:30:58+00:00","dateModified":"2017-06-11T20:23:35+00:00","author":{"@id":"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d"},"description":"This article gives an overview of Zend Framework 2's event manager. Learn how to attach event listeners and trigger events with ZF2's event manager.","breadcrumb":{"@id":"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/codingexplained.com\/coding\/php\/zend-framework\/zend-framework-2-event-manager#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/codingexplained.com\/"},{"@type":"ListItem","position":2,"name":"Zend Framework 2 Event Manager"}]},{"@type":"WebSite","@id":"https:\/\/codingexplained.com\/#website","url":"https:\/\/codingexplained.com\/","name":"Coding Explained","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/codingexplained.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d","name":"Bo Andersen","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/codingexplained.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g","caption":"Bo Andersen"},"description":"I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!","sameAs":["https:\/\/codingexplained.com","https:\/\/www.facebook.com\/codingexplained","https:\/\/www.linkedin.com\/in\/ba0708","https:\/\/twitter.com\/codingexplained","https:\/\/www.youtube.com\/c\/codingexplained"],"url":"https:\/\/codingexplained.com\/author\/andy"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p3mJkW-7N","_links":{"self":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/483"}],"collection":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/comments?post=483"}],"version-history":[{"count":7,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/483\/revisions"}],"predecessor-version":[{"id":3050,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/483\/revisions\/3050"}],"wp:attachment":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/media?parent=483"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/categories?post=483"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/tags?post=483"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/series?post=483"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}