Zend_EventManager-EventManager.xml 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.event-manager.event-manager">
  4. <title>The EventManager</title>
  5. <sect2 id="zend.event-manager.event-manager.intro">
  6. <title>Overview</title>
  7. <para>
  8. <classname>Zend_EventManager</classname> is a component designed for the following use
  9. cases:
  10. </para>
  11. <itemizedlist>
  12. <listitem>
  13. <para>
  14. Implementing simple subject/observer patterns.
  15. </para>
  16. </listitem>
  17. <listitem>
  18. <para>
  19. Implementing Aspect-Oriented designs.
  20. </para>
  21. </listitem>
  22. <listitem>
  23. <para>
  24. Implementing event-driven architectures.
  25. </para>
  26. </listitem>
  27. </itemizedlist>
  28. <para>
  29. The basic architecture allows you to attach and detach listeners to named events, both on
  30. a per-instance basis as well as statically; trigger events; and interrupt execution of
  31. listeners.
  32. </para>
  33. </sect2>
  34. <sect2 id="zend.event-manager.event-manager.quick-start">
  35. <title>Quick Start</title>
  36. <para>
  37. Typically, you will compose a <classname>Zend_EventManager_EventManager</classname> instance in a class.
  38. </para>
  39. <programlisting language="php"><![CDATA[
  40. class Foo
  41. {
  42. protected $events;
  43. public function events(Zend_EventManager_EventCollection $events = null)
  44. {
  45. if (null !== $events) {
  46. $this->events = $events;
  47. } elseif (null === $this->events) {
  48. $this->events = new Zend_EventManager_EventManager(__CLASS__);
  49. }
  50. return $this->events;
  51. }
  52. }
  53. ]]></programlisting>
  54. <para>
  55. The above allows users to access the <classname>EventManager</classname> instance, or
  56. reset it with a new instance; if one does not exist, it will be lazily instantiated
  57. on-demand.
  58. </para>
  59. <para>
  60. An <classname>EventManager</classname> is really only interesting if it triggers some
  61. events. Basic triggering takes three arguments: the event name, which is usually the
  62. current function/method name; the "context", which is usually the current object
  63. instance; and the arguments, which are usually the arguments provided to the current
  64. function/method.
  65. </para>
  66. <programlisting language="php"><![CDATA[
  67. class Foo
  68. {
  69. // ... assume events definition from above
  70. public function bar($baz, $bat = null)
  71. {
  72. $params = compact('baz', 'bat');
  73. $this->events()->trigger(__FUNCTION__, $this, $params);
  74. }
  75. }
  76. ]]></programlisting>
  77. <para>
  78. In turn, triggering events is only interesting if something is listening for the event.
  79. Listeners attach to the <classname>EventManager</classname>, specifying a named event
  80. and the callback to notify. The callback receives a <classname>Zend_EventManager_Event</classname>
  81. object, which has accessors for retrieving the event name, context, and parameters.
  82. Let's add a listener, and trigger the event.
  83. </para>
  84. <programlisting language="php"><![CDATA[
  85. $log = Zend_Log::factory($someConfig);
  86. $foo = new Foo();
  87. $foo->events()->attach('bar', function ($e) use ($log) {
  88. $event = $e->getName();
  89. $target = get_class($e->getTarget());
  90. $params = json_encode($e->getParams());
  91. $log->info(sprintf(
  92. '%s called on %s, using params %s',
  93. $event,
  94. $target,
  95. $params
  96. ));
  97. });
  98. // Results in log message:
  99. $foo->bar('baz', 'bat');
  100. // reading: bar called on Foo, using params {"baz" : "baz", "bat" : "bat"}"
  101. ]]></programlisting>
  102. <para>
  103. Note that the second argument to <methodname>attach()</methodname> is any valid callback;
  104. an anonymous function is shown in the example in order to keep the example
  105. self-contained. However, you could also utilize a valid function name, a functor, a
  106. string referencing a static method, or an array callback with a named static method or
  107. instance method. Again, any PHP callback is valid.
  108. </para>
  109. <para>
  110. Sometimes you may want to specify listeners without yet having an object instance of the
  111. class composing an <classname>EventManager</classname>. The
  112. <classname>Zend_EventManager_StaticEventManager</classname> allows you to do this. The call to
  113. <methodname>attach</methodname> is identical to the <classname>EventManager</classname>,
  114. but expects an additional parameter at the beginning: a named instance. Remember the
  115. example of composing an <classname>EventManager</classname>, how we passed it
  116. <constant>__CLASS__</constant>? That value, or any strings you provide in an array to
  117. the constructor, may be used to identify an instance when using the
  118. <classname>StaticEventManager</classname>. As an example, we could change the above
  119. example to attach statically:
  120. </para>
  121. <programlisting language="php"><![CDATA[
  122. $log = Zend_Log::factory($someConfig);
  123. $events = Zend_EventManager_StaticEventManager::getInstance();
  124. $events->attach('Foo', 'bar', function ($e) use ($log) {
  125. $event = $e->getName();
  126. $target = get_class($e->getTarget());
  127. $params = json_encode($e->getParams());
  128. $log->info(sprintf(
  129. '%s called on %s, using params %s',
  130. $event,
  131. $target,
  132. $params
  133. ));
  134. });
  135. // Later, instantiate Foo:
  136. $foo = new Foo();
  137. // And we can still trigger the above event:
  138. $foo->bar('baz', 'bat');
  139. // results in log message:
  140. // bar called on Foo, using params {"baz" : "baz", "bat" : "bat"}"
  141. ]]></programlisting>
  142. <para>
  143. The <classname>EventManager</classname> also provides the ability to detach listeners,
  144. short-circuit execution of an event either from within a listener or by testing return
  145. values of listeners, test and loop through the results returned by listeners, prioritize
  146. listeners, and more. Many of these features are detailed in the examples.
  147. </para>
  148. <sect3 id="zend.event-manager.event-manager.quick-start.wildcard">
  149. <title>Wildcard Listeners</title>
  150. <para>
  151. Sometimes you'll want to attach the same listener to many events or to all events of
  152. a given instance -- or potentially, with the static manager, many contexts, and many
  153. events. The <classname>EventManager</classname> component allows for this.
  154. </para>
  155. <example id="zend.event-manager.event-manager.quick-start.wildcard.many">
  156. <title>Attaching to many events at once</title>
  157. <programlisting language="php"><![CDATA[
  158. $events = new Zend_EventManager_EventManager();
  159. $events->attach(array('these', 'are', 'event', 'names'), $callback);
  160. ]]></programlisting>
  161. <para>
  162. Note that if you specify a priority, that priority will be used for all events
  163. specified.
  164. </para>
  165. </example>
  166. <example id="zend.event-manager.event-manager.quick-start.wildcard.wildcard">
  167. <title>Attaching using the wildcard</title>
  168. <programlisting language="php"><![CDATA[
  169. $events = new Zend_EventManager_EventManager();
  170. $events->attach('*', $callback);
  171. ]]></programlisting>
  172. <para>
  173. Note that if you specify a priority, that priority will be used for this
  174. listener for any event triggered.
  175. </para>
  176. <para>
  177. What the above specifies is that <emphasis>any</emphasis> event triggered will
  178. result in notification of this particular listener.
  179. </para>
  180. </example>
  181. <example id="zend.event-manager.event-manager.quick-start.wildcard.static-many">
  182. <title>Attaching to many events at once via the StaticEventManager</title>
  183. <programlisting language="php"><![CDATA[
  184. $events = Zend_EventManager_StaticEventManager::getInstance();
  185. // Attach to many events on the context "foo"
  186. $events->attach('foo', array('these', 'are', 'event', 'names'), $callback);
  187. // Attach to many events on the contexts "foo" and "bar"
  188. $events->attach(array('foo', 'bar'), array('these', 'are', 'event', 'names'), $callback);
  189. ]]></programlisting>
  190. <para>
  191. Note that if you specify a priority, that priority will be used for all events
  192. specified.
  193. </para>
  194. </example>
  195. <example id="zend.event-manager.event-manager.quick-start.wildcard.static-wildcard">
  196. <title>Attaching to many events at once via the StaticEventManager</title>
  197. <programlisting language="php"><![CDATA[
  198. $events = Zend_EventManager_StaticEventManager::getInstance();
  199. // Attach to all events on the context "foo"
  200. $events->attach('foo', '*', $callback);
  201. // Attach to all events on the contexts "foo" and "bar"
  202. $events->attach(array('foo', 'bar'), '*', $callback);
  203. ]]></programlisting>
  204. <para>
  205. Note that if you specify a priority, that priority will be used for all events
  206. specified.
  207. </para>
  208. <para>
  209. The above is specifying that for the contexts "foo" and "bar", the specified
  210. listener should be notified for any event they trigger.
  211. </para>
  212. </example>
  213. </sect3>
  214. </sect2>
  215. <sect2 id="zend.event-manager.event-manager.options">
  216. <title>Configuration Options</title>
  217. <variablelist>
  218. <title>Zend_EventManager_EventManager Options</title>
  219. <varlistentry>
  220. <term>identifier</term>
  221. <listitem>
  222. <para>
  223. A string or array of strings to which the given
  224. <classname>EventManager</classname> instance can answer when accessed via
  225. the <classname>StaticEventManager</classname>.
  226. </para>
  227. </listitem>
  228. </varlistentry>
  229. <varlistentry>
  230. <term>event_class</term>
  231. <listitem>
  232. <para>
  233. The name of an alternate <classname>Zend_EventManager_Event</classname> class to use for
  234. representing events passed to listeners.
  235. </para>
  236. </listitem>
  237. </varlistentry>
  238. <varlistentry>
  239. <term>static_connections</term>
  240. <listitem>
  241. <para>
  242. An instance of a <interfacename>Zend_EventManager_StaticEventCollection</interfacename>
  243. instance to use when triggering events. By default, this will use
  244. the global <classname>Zend_EventManager_StaticEventManager</classname> instance, but that can
  245. be overridden by passing a value to this method. A <constant>null</constant>
  246. value will prevent the instance from triggering any further statically
  247. attached listeners.
  248. </para>
  249. </listitem>
  250. </varlistentry>
  251. </variablelist>
  252. </sect2>
  253. <sect2 id="zend.event-manager.event-manager.methods">
  254. <title>Available Methods</title>
  255. <variablelist>
  256. <varlistentry id="zend.event-manager.event-manager.methods.constructor">
  257. <term>__construct</term>
  258. <listitem>
  259. <methodsynopsis>
  260. <methodname>__construct</methodname>
  261. <methodparam>
  262. <funcparams>null|string|int $identifier</funcparams>
  263. </methodparam>
  264. </methodsynopsis>
  265. <para>
  266. Constructs a new <classname>EventManager</classname> instance, using the
  267. given identifier, if provided, for purposes of static attachment.
  268. </para>
  269. </listitem>
  270. </varlistentry>
  271. <varlistentry id="zend.event-manager.event-manager.methods.set-event-class">
  272. <term>setEventClass</term>
  273. <listitem>
  274. <methodsynopsis>
  275. <methodname>setEventClass</methodname>
  276. <methodparam>
  277. <funcparams>string $class</funcparams>
  278. </methodparam>
  279. </methodsynopsis>
  280. <para>
  281. Provide the name of an alternate <classname>Zend_EventManager_Event</classname> class to use
  282. when creating events to pass to triggered listeners.
  283. </para>
  284. </listitem>
  285. </varlistentry>
  286. <varlistentry id="zend.event-manager.event-manager.methods.set-static-connections">
  287. <term>setStaticConnections</term>
  288. <listitem>
  289. <methodsynopsis>
  290. <methodname>setStaticConnections</methodname>
  291. <methodparam>
  292. <funcparams>Zend_EventManager_StaticEventCollection $connections = null</funcparams>
  293. </methodparam>
  294. </methodsynopsis>
  295. <para>
  296. An instance of a <interfacename>Zend_EventManager_StaticEventCollection</interfacename>
  297. instance to use when triggering events. By default, this will use
  298. the global <classname>Zend_EventManager_StaticEventManager</classname> instance, but that can
  299. be overridden by passing a value to this method. A <constant>null</constant>
  300. value will prevent the instance from triggering any further statically
  301. attached listeners.
  302. </para>
  303. </listitem>
  304. </varlistentry>
  305. <varlistentry id="zend.event-manager.event-manager.methods.get-static-connections">
  306. <term>getStaticConnections</term>
  307. <listitem>
  308. <methodsynopsis>
  309. <methodname>getStaticConnections</methodname>
  310. <void/>
  311. </methodsynopsis>
  312. <para>
  313. Returns the currently attached
  314. <interfacename>Zend_EventManager_StaticEventCollection</interfacename> instance, lazily
  315. retrieving the global <classname>Zend_EventManager_StaticEventManager</classname> instance if
  316. none is attached and usage of static listeners hasn't been disabled by
  317. passing a <constant>null</constant> value to <link
  318. linkend="zend.event-manager.event-manager.methods.set-static-connections">setStaticConnections()</link>.
  319. Returns either a boolean <constant>false</constant> if static listeners are
  320. disabled, or a <interfacename>StaticEventCollection</interfacename> instance
  321. otherwise.
  322. </para>
  323. </listitem>
  324. </varlistentry>
  325. <varlistentry id="zend.event-manager.event-manager.methods.trigger">
  326. <term>trigger</term>
  327. <listitem>
  328. <methodsynopsis>
  329. <methodname>trigger</methodname>
  330. <methodparam>
  331. <funcparams>string $event, mixed $target, mixed $argv, callback $callback</funcparams>
  332. </methodparam>
  333. </methodsynopsis>
  334. <para>
  335. Triggers all listeners to a named event. The recommendation is to use the
  336. current function/method name for <varname>$event</varname>, appending it
  337. with values such as ".pre", ".post", etc. as needed.
  338. <varname>$context</varname> should be the current object instance, or the
  339. name of the function if not triggering within an object.
  340. <varname>$params</varname> should typically be an associative array or
  341. <classname>ArrayAccess</classname> instance; we recommend using the
  342. parameters passed to the function/method (<function>compact()</function> is
  343. often useful here). This method can also take a callback and behave in the
  344. same way as <methodname>triggerUntil()</methodname>.
  345. </para>
  346. <para>
  347. The method returns an instance of <classname>Zend_EventManager_ResponseCollection</classname>,
  348. which may be used to introspect return values of the various listeners, test
  349. for short-circuiting, and more.
  350. </para>
  351. </listitem>
  352. </varlistentry>
  353. <varlistentry id="zend.event-manager.event-manager.methods.trigger-until">
  354. <term>triggerUntil</term>
  355. <listitem>
  356. <methodsynopsis>
  357. <methodname>triggerUntil</methodname>
  358. <methodparam>
  359. <funcparams>string $event, mixed $context, mixed $argv, callback
  360. $callback</funcparams>
  361. </methodparam>
  362. </methodsynopsis>
  363. <para>
  364. Triggers all listeners to a named event, just like <link
  365. linkend="zend.event-manager.event-manager.methods.trigger">trigger()</link>,
  366. with the addition that it passes the return value from each listener to
  367. <varname>$callback</varname>; if <varname>$callback</varname> returns a
  368. boolean <constant>true</constant> value, execution of the listeners is
  369. interrupted. You can test for this using <code>$result-&gt;stopped()</code>.
  370. </para>
  371. </listitem>
  372. </varlistentry>
  373. <varlistentry id="zend.event-manager.event-manager.methods.attach">
  374. <term>attach</term>
  375. <listitem>
  376. <methodsynopsis>
  377. <methodname>attach</methodname>
  378. <methodparam>
  379. <funcparams>string $event, callback $callback, int $priority</funcparams>
  380. </methodparam>
  381. </methodsynopsis>
  382. <para>
  383. Attaches <varname>$callback</varname> to the
  384. <classname>Zend_EventManager_EventManager</classname> instance, listening for the event
  385. <varname>$event</varname>. If a <varname>$priority</varname> is provided,
  386. the listener will be inserted into the internal listener stack using that
  387. priority; higher values execute earliest. (Default priority is "1", and
  388. negative priorities are allowed.)
  389. </para>
  390. <para>
  391. The method returns an instance of
  392. <classname>Zend_Stdlib_CallbackHandler</classname>; this value can later be
  393. passed to <methodname>detach()</methodname> if desired.
  394. </para>
  395. </listitem>
  396. </varlistentry>
  397. <varlistentry id="zend.event-manager.event-manager.methods.attach-aggregate">
  398. <term>attachAggregate</term>
  399. <listitem>
  400. <methodsynopsis>
  401. <methodname>attachAggregate</methodname>
  402. <methodparam>
  403. <funcparams>string|Zend_EventManager_ListenerAggregate $aggregate</funcparams>
  404. </methodparam>
  405. </methodsynopsis>
  406. <para>
  407. If a string is passed for <varname>$aggregate</varname>, instantiates that
  408. class. The <varname>$aggregate</varname> is then passed the
  409. <classname>EventManager</classname> instance to its
  410. <methodname>attach()</methodname> method so that it may register listeners.
  411. </para>
  412. <para>
  413. The <classname>ListenerAggregate</classname> instance is returned.
  414. </para>
  415. </listitem>
  416. </varlistentry>
  417. <varlistentry id="zend.event-manager.event-manager.methods.detach">
  418. <term>detach</term>
  419. <listitem>
  420. <methodsynopsis>
  421. <methodname>detach</methodname>
  422. <methodparam>
  423. <funcparams>Zend_Stdlib_CallbackHandler $listener</funcparams>
  424. </methodparam>
  425. </methodsynopsis>
  426. <para>
  427. Scans all listeners, and detaches any that match <varname>$listener</varname>
  428. so that they will no longer be triggered.
  429. </para>
  430. <para>
  431. Returns a boolean <constant>true</constant> if any listeners have been
  432. identified and unsubscribed, and a boolean <constant>false</constant>
  433. otherwise.
  434. </para>
  435. </listitem>
  436. </varlistentry>
  437. <varlistentry id="zend.event-manager.event-manager.methods.detach-aggregate">
  438. <term>detachAggregate</term>
  439. <listitem>
  440. <methodsynopsis>
  441. <methodname>detachAggregate</methodname>
  442. <methodparam>
  443. <funcparams>Zend_EventManager_ListenerAggregate $aggregate</funcparams>
  444. </methodparam>
  445. </methodsynopsis>
  446. <para>
  447. Loops through all listeners of all events to identify listeners that are
  448. represented by the aggregate; for all matches, the listeners will be removed.
  449. </para>
  450. <para>
  451. Returns a boolean <constant>true</constant> if any listeners have been
  452. identified and unsubscribed, and a boolean <constant>false</constant>
  453. otherwise.
  454. </para>
  455. </listitem>
  456. </varlistentry>
  457. <varlistentry id="zend.event-manager.event-manager.methods.get-events">
  458. <term>detachAggregate</term>
  459. <listitem>
  460. <methodsynopsis>
  461. <methodname>getEvents</methodname>
  462. <void/>
  463. </methodsynopsis>
  464. <para>
  465. Returns an array of all event names that have listeners attached.
  466. </para>
  467. </listitem>
  468. </varlistentry>
  469. <varlistentry id="zend.event-manager.event-manager.methods.get-listeners">
  470. <term>getListeners</term>
  471. <listitem>
  472. <methodsynopsis>
  473. <methodname>getListeners</methodname>
  474. <methodparam>
  475. <funcparams>string $event</funcparams>
  476. </methodparam>
  477. </methodsynopsis>
  478. <para>
  479. Returns a <classname>Zend_Stdlib_PriorityQueue</classname> instance of all
  480. listeners attached to <varname>$event</varname>.
  481. </para>
  482. </listitem>
  483. </varlistentry>
  484. <varlistentry id="zend.event-manager.event-manager.methods.clear-listeners">
  485. <term>clearListeners</term>
  486. <listitem>
  487. <methodsynopsis>
  488. <methodname>clearListeners</methodname>
  489. <methodparam>
  490. <funcparams>string $event</funcparams>
  491. </methodparam>
  492. </methodsynopsis>
  493. <para>
  494. Removes all listeners attached to <varname>$event</varname>.
  495. </para>
  496. </listitem>
  497. </varlistentry>
  498. <varlistentry id="zend.event-manager.event-manager.methods.prepare-args">
  499. <term>prepareArgs</term>
  500. <listitem>
  501. <methodsynopsis>
  502. <methodname>prepareArgs</methodname>
  503. <methodparam>
  504. <funcparams>array $args</funcparams>
  505. </methodparam>
  506. </methodsynopsis>
  507. <para>
  508. Creates an <classname>ArrayObject</classname> from the provided
  509. <varname>$args</varname>. This can be useful if you want yours listeners
  510. to be able to modify arguments such that later listeners or the triggering
  511. method can see the changes.
  512. </para>
  513. </listitem>
  514. </varlistentry>
  515. </variablelist>
  516. </sect2>
  517. <sect2 id="zend.event-manager.event-manager.examples">
  518. <title>Examples</title>
  519. <example id="zend.event-manager.event-manager.examples.modifying-args">
  520. <title>Modifying Arguments</title>
  521. <para>
  522. Occasionally it can be useful to allow listeners to modify the arguments they
  523. receive so that later listeners or the calling method will receive those changed
  524. values.
  525. </para>
  526. <para>
  527. As an example, you might want to pre-filter a date that you know will arrive as a
  528. string and convert it to a <classname>DateTime</classname> argument.
  529. </para>
  530. <para>
  531. To do this, you can pass your arguments to <methodname>prepareArgs()</methodname>,
  532. and pass this new object when triggering an event. You will then pull that value
  533. back into your method.
  534. </para>
  535. <programlisting language="php"><![CDATA[
  536. class ValueObject
  537. {
  538. // assume a composed event manager
  539. function inject(array $values)
  540. {
  541. $argv = compact('values');
  542. $argv = $this->events()->prepareArgs($argv);
  543. $this->events()->trigger(__FUNCTION__, $this, $argv);
  544. $date = isset($argv['values']['date']) ? $argv['values']['date'] : new DateTime('now');
  545. // ...
  546. }
  547. }
  548. $v = new ValueObject();
  549. $v->events()->attach('inject', function($e) {
  550. $values = $e->getParam('values');
  551. if (!$values) {
  552. return;
  553. }
  554. if (!isset($values['date'])) {
  555. $values['date'] = new DateTime('now');
  556. return;
  557. }
  558. $values['date'] = new Datetime($values['date']);
  559. });
  560. $v->inject(array(
  561. 'date' => '2011-08-10 15:30:29',
  562. ));
  563. ]]></programlisting>
  564. </example>
  565. <example id="zend.event-manager.event-manager.examples.short-circuiting">
  566. <title>Short Circuiting</title>
  567. <para>
  568. One common use case for events is to trigger listeners until either one indicates no
  569. further processing should be done, or until a return value meets specific criteria.
  570. As examples, if an event creates a Response object, it may want execution to stop.
  571. </para>
  572. <programlisting language="php"><![CDATA[
  573. $listener = function($e) {
  574. // do some work
  575. // Stop propagation and return a response
  576. $e->stopPropagation(true);
  577. return $response;
  578. };
  579. ]]></programlisting>
  580. <para>
  581. Alternately, we could do the check from the method triggering the event.
  582. </para>
  583. <programlisting language="php"><![CDATA[
  584. class Foo implements Dispatchable
  585. {
  586. // assume composed event manager
  587. public function dispatch(Request $request, Response $response = null)
  588. {
  589. $argv = compact('request', 'response');
  590. $results = $this->events()->triggerUntil(__FUNCTION__, $this, $argv, function($v) {
  591. return ($v instanceof Response);
  592. });
  593. }
  594. }
  595. ]]></programlisting>
  596. <para>
  597. Typically, you may want to return a value that stopped execution, or use it some
  598. way. Both <methodname>trigger()</methodname> and
  599. <methodname>triggerUntil()</methodname> return a
  600. <classname>Zend_EventManager_ResponseCollection</classname> instance; call its
  601. <methodname>stopped()</methodname> method to test if execution was stopped, and
  602. <methodname>last()</methodname> method to retrieve the return value from the last
  603. executed listener:
  604. </para>
  605. <programlisting language="php"><![CDATA[
  606. class Foo implements Dispatchable
  607. {
  608. // assume composed event manager
  609. public function dispatch(Request $request, Response $response = null)
  610. {
  611. $argv = compact('request', 'response');
  612. $results = $this->events()->triggerUntil(__FUNCTION__, $this, $argv, function($v) {
  613. return ($v instanceof Response);
  614. });
  615. // Test if execution was halted, and return last result:
  616. if ($results->stopped()) {
  617. return $results->last();
  618. }
  619. // continue...
  620. }
  621. }
  622. ]]></programlisting>
  623. </example>
  624. <example id="zend.event-manager.event-manager.examples.priority">
  625. <title>Assigning Priority to Listeners</title>
  626. <para>
  627. One use case for the <classname>EventManager</classname> is for implementing caching
  628. systems. As such, you often want to check the cache early, and save to it late.
  629. </para>
  630. <para>
  631. The third argument to <methodname>attach()</methodname> is a priority value. The
  632. higher this number, the earlier that listener will execute; the lower it is, the
  633. later it executes. The value defaults to 1, and values will trigger in the order
  634. registered within a given priority.
  635. </para>
  636. <para>
  637. So, to implement a caching system, our method will need to trigger an event at
  638. method start as well as at method end. At method start, we want an event that will
  639. trigger early; at method end, an event should trigger late.
  640. </para>
  641. <para>
  642. Here is the class in which we want caching:
  643. </para>
  644. <programlisting language="php"><![CDATA[
  645. class SomeValueObject
  646. {
  647. // assume it composes an event manager
  648. public function get($id)
  649. {
  650. $params = compact('id');
  651. $results = $this->events()->trigger('get.pre', $this, $params);
  652. // If an event stopped propagation, return the value
  653. if ($results->stopped()) {
  654. return $results->last();
  655. }
  656. // do some work...
  657. $params['__RESULT__'] = $someComputedContent;
  658. $this->events()->trigger('get.post', $this, $params);
  659. }
  660. }
  661. ]]></programlisting>
  662. <para>
  663. Now, let's create a <interfacename>ListenerAggregate</interfacename> that can handle
  664. caching for us:
  665. </para>
  666. <programlisting language="php"><![CDATA[
  667. class CacheListener implements Zend_EventManager_ListenerAggregate
  668. {
  669. protected $cache;
  670. public function __construct(Cache $cache)
  671. {
  672. $this->cache = $cache;
  673. }
  674. public function attach(Zend_EventManager_EventCollection $events)
  675. {
  676. $events->attach('get.pre', array($this, 'load'), 100);
  677. $events->attach('get.post', array($this, 'save'), -100);
  678. }
  679. public function load($e)
  680. {
  681. $id = get_class($e->getTarget()) . '-' . json_encode($e->getParams());
  682. if (false !== ($content = $this->cache->load($id))) {
  683. $e->stopPropagation(true);
  684. return $content;
  685. }
  686. }
  687. public function save($e)
  688. {
  689. $params = $e->getParams();
  690. $content = $params['__RESULT__'];
  691. unset($params['__RESULT__']);
  692. $id = get_class($e->getTarget()) . '-' . json_encode($params);
  693. $this->cache->save($content, $id);
  694. }
  695. }
  696. ]]></programlisting>
  697. <para>
  698. We can then attach the aggregate to an instance.
  699. </para>
  700. <programlisting language="php"><![CDATA[
  701. $value = new SomeValueObject();
  702. $cacheListener = new CacheListener($cache);
  703. $value->events()->attachAggregate($cacheListener);
  704. ]]></programlisting>
  705. <para>
  706. Now, as we call <methodname>get()</methodname>, if we have a cached entry, it will
  707. be returned immediately; if not, a computed entry will be cached when we complete
  708. the method.
  709. </para>
  710. </example>
  711. </sect2>
  712. </sect1>