Question

i use this code for trigger an event:

$input = array(1,2,3);
$result = $EventManager->trigger('onChangeArray',$this,array('values'=>$input));
$c = $result->count();
$final = array();
for($i=0; $i<$c; $i++)
    $final = array_merge($final , $result->pop());

i want change this array in attach function. if i add to array, $final contain all values Properly; but i want to remove a value from $final in attach function. i need to call attach functions for nesting that each time the function call with returned array from previous function. i use this code for add value to array in BootStrap:

$SharedManager->attach('Identifier', 'onChangeArray', function($e) {
     $values = $e->getParam('values');
     $values[] = 4 ;
     return $values;
});

if possible please help me for remove from array.

Was it helpful?

Solution

Ok, I think I get it now. Instead of getting the returned values from the result collection as you're doing with your for loop, create an event object containing the values, and have your listeners act on that array instead.

$input = array(1,2,3);
$event = new \Zend\EventManager\Event('onChangeArray', $this, array('values' => $input));
$EventManager->trigger($event);

$values = $event->getParam('values');

Because the event is passed by reference, your listeners don't need to return anything, they just need to act on the values parameter. Consider the following two listeners, one adding and one removing from the array. Neither return a value directly, they both act on the values param contained in the $event they were given

$SharedManager->attach('Identifier', 'onChangeArray', function($e) {
    $values = $e->getParam('values');
    // add value 4 to array
    $values[] = 4 ;
    $e->setParam('values', $values);
});

$SharedManager->attach('Identifier', 'onChangeArray', function($e) {
    $values = $e->getParam('values');
    // remove value of 3 from array
    if (($key = array_search(3, $values)) !== false) {
        unset($values[$key]);
    }
    $e->setParam('values', $values);
});

After triggering the event as directed in the first step, you'll find that the values param in your event contains the final array...

// ..
$EventManager->trigger($event);
$values = $event->getParam('values');

\Zend\Debug\Debug::dump($values);
// result
array(3) {
    [0] => int(1)
    [1] => int(2)
    [3] => int(4)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top