CakeEventManager::attach PHP Method

attach() public method

Adds a new listener to an event. Listeners
public attach ( callback | CakeEventListener $callable, string $eventKey = null, array $options = [] ) : void
$callable callback | CakeEventListener PHP valid callback type or instance of CakeEventListener to be called when the event named with $eventKey is triggered. If a CakeEventListener instance is passed, then the `implementedEvents` method will be called on the object to register the declared events individually as methods to be managed by this class. It is possible to define multiple event handlers per event name.
$eventKey string The event unique identifier name with which the callback will be associated. If $callable is an instance of CakeEventListener this argument will be ignored
$options array used to set the `priority` and `passParams` flags to the listener. Priorities are handled like queues, and multiple attachments added to the same priority queue will be treated in the order of insertion. `passParams` means that the event data property will be converted to function arguments when the listener is called. If $called is an instance of CakeEventListener, this parameter will be ignored
return void
    public function attach($callable, $eventKey = null, $options = array())
    {
        if (!$eventKey && !$callable instanceof CakeEventListener) {
            throw new InvalidArgumentException(__d('cake_dev', 'The eventKey variable is required'));
        }
        if ($callable instanceof CakeEventListener) {
            $this->_attachSubscriber($callable);
            return;
        }
        $options = $options + array('priority' => static::$defaultPriority, 'passParams' => false);
        $this->_listeners[$eventKey][$options['priority']][] = array('callable' => $callable, 'passParams' => $options['passParams']);
    }

Usage Example

 /**
  * Load a single event class attached to Crud
  *
  * @param string $name
  * @return void
  */
 protected function _loadListener($name)
 {
     $subject = $this->_getSubject();
     $config = $this->config(sprintf('listenerClassMap.%s', $name));
     list($plugin, $class) = pluginSplit($config, true);
     App::uses($class, $plugin . 'Controller/Event');
     // Make sure to cleanup duplicate events
     if (isset($this->_listeners[$name])) {
         $this->_eventManager->detach($this->_listeners[$name]);
         unset($this->_listeners[$name]);
     }
     $this->_listeners[$name] = new $class($subject);
     $this->_eventManager->attach($this->_listeners[$name]);
 }
All Usage Examples Of CakeEventManager::attach