PHP code example of buonaparte / bnp-lazy-listener

1. Go to this page and download the library: Download buonaparte/bnp-lazy-listener library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

buonaparte / bnp-lazy-listener example snippets


class PlainPhpObjectWithDependencies
{
    // Your Dependencies

    public function __construct($aDependency, $anotherDependency)
    {
        // ...
    }

    public function setExtraDependency($dependency)
    {
        // ...
    }

    public function onFoo(Zend\EventManager\EventInterface $e)
    {
        // do some complex stuff ...
        $e->setParam('foo', 'bar');
    }

    public function onBar(Zend\EventManager\EventInterface $e)
    {
        // do some complex stuff ...
        $e->setParam('bar', 'baz');
    }

    public function onBaz(Zend\EventManager\EventInterface $e)
    {
        // do some complex stuff ...
        $e->setParam('baz', array_merge($e->getParam('baz', array()), array('element'));
    }
}

use Zend\EventManager\EventManager;
use Zend\EventManager\Event;
use BnpLazyListener\LazyListenerAggregate;

$events = new EventManager();

$events->attach(new LazyListenerAggregate(
    function () use ($aDependency, $anotherDependency, $dependency) {
        $listener = new PlainPhpObjectWithDependencies($aDependency, $anotherDependency);
        $listener->setExtraDependency($dependency);

        return $listener;
    },
    array(
        'foo' => 'onFoo',
        'bar' => array('onBar', 1000),
        'baz' => array(
            'onBaz',
            array('onBaz', -99)
        )
    )
));

$events->trigger(new Event('an_event'));

// PlainPhpObjectWithDependencies gets instantiated only now
$events->trigger(new Event('foo'));

use Zend\ServiceManager\ServiceManager;
use Zend\EventManager\EventManager;
use BnpLazyListener\ServicesListenerAggregateCollection;

$delegates = array(
    'a_listener_aggregate_service',
    'MyApp\Factory\ListenerAggregateFactoryService',
    array(
        'PlainPhpObjectWithDependencies',
        array(
            'foo' => 'onFoo',
            'bar' => array('onBar', 1000),
            'baz' => array(
                'onBaz',
                array('onBaz', -99)
            )
        )
    )
);

$services = new ServiceManager();
// declare your a_listener_aggregate_service and PlainPhpObjectWithDependencies services in the container

$listener = new ServicesListenerAggregateCollection($delegates);
$listener->setServiceLocator($services);

$events = new EventManager();
$events->attach($listener);

$events->trigger(new Event('an_event'));

// PlainPhpObjectWithDependencies gets pulled from the locator only now
$events->trigger(new Event('bar'));
bash
    $ php composer.phar update