1<?php 2 3/** 4 * Hoa 5 * 6 * 7 * @license 8 * 9 * New BSD License 10 * 11 * Copyright © 2007-2017, Hoa community. All rights reserved. 12 * 13 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions are met: 15 * * Redistributions of source code must retain the above copyright 16 * notice, this list of conditions and the following disclaimer. 17 * * Redistributions in binary form must reproduce the above copyright 18 * notice, this list of conditions and the following disclaimer in the 19 * documentation and/or other materials provided with the distribution. 20 * * Neither the name of the Hoa nor the names of its contributors may be 21 * used to endorse or promote products derived from this software without 22 * specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE 28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 * POSSIBILITY OF SUCH DAMAGE. 35 */ 36 37namespace Hoa\Event; 38 39/** 40 * Trait \Hoa\Event\Listens. 41 * 42 * Implementation of a listener. 43 * 44 * @copyright Copyright © 2007-2017 Hoa community 45 * @license New BSD License 46 */ 47trait Listens 48{ 49 /** 50 * Listener instance. 51 * 52 * @var \Hoa\Event\Listener 53 */ 54 protected $_listener = null; 55 56 57 58 /** 59 * Attach a callable to a listenable component. 60 * 61 * @param string $listenerId Listener ID. 62 * @param mixed $callable Callable. 63 * @return \Hoa\Event\Listenable 64 */ 65 public function on($listenerId, $callable) 66 { 67 $listener = $this->getListener(); 68 69 if (null === $listener) { 70 throw new Exception( 71 'Cannot attach a callable to the listener %s because ' . 72 'it has not been initialized yet.', 73 0, 74 get_class($this) 75 ); 76 } 77 78 $listener->attach($listenerId, $callable); 79 80 return $this; 81 } 82 83 /** 84 * Set listener. 85 * 86 * @param \Hoa\Event\Listener $listener Listener. 87 * @return \Hoa\Event\Listener 88 */ 89 protected function setListener(Listener $listener) 90 { 91 $old = $this->_listener; 92 $this->_listener = $listener; 93 94 return $old; 95 } 96 97 /** 98 * Get listener. 99 * 100 * @return \Hoa\Event\Listener 101 */ 102 protected function getListener() 103 { 104 return $this->_listener; 105 } 106} 107