PHP code example of antares / pool

1. Go to this page and download the library: Download antares/pool 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/ */

    

antares / pool example snippets


interface PoolInterface
{
    // Associate a resource to an id
    public function set($id, $generator, $eventsCallbacks = null);

    // Get an instance of the resource
    public function get($id);

    // Free the instance of the resource
    public function dispose($instance);

    // Clear the pool
    public function clear();

    // Set a set of callbacks for the events a resource can trigger
    public function addEventsCallbacks($id, $callbacks);

    // Set a callback to call when an event is triggered for given resource
    public function addEventCallback($id, $event, $callback);
}

use Pool\Pool;

class Foo {}

$pool = new Pool(); // Instantiate the pool
$pool->set('foo', function() { return new Foo(); }); // Assign to the id 'foo' a generator returning an instance of Foo

// If an instance is already available, the pool will return it
// Else, a new instance will be created
$foo = $pool->get('foo');

// We don't need $foo anymore, so the instance can be released
// It will be available from the pool again
$pool->dispose($foo);


use Pool\StaticPool;

class Foo {}

$pool = new StaticPool();

if (!$pool->isAlreadyDefined()) {
    $pool->set('foo', function() { return new Foo(); });
}

$foo = $pool->get('foo');
$pool->dispose($foo);

use Pool\PoolInterface;

$pool = new Pool\Pool();

$callbacks = [
    PoolInterface::EVENT_GET => [function($instance) {}],
    PoolInterface::EVENT_DISPOSE => [function($instance) {}]
];

// 1. Define it with the generator
$pool->set('foo', function() { return new Foo(); }, $callbacks);

// 2. Define each event
$pool->addEventCallback('foo', PoolInterface::EVENT_GET, $callbacks[PoolInterface::EVENT_GET][0]);
$pool->addEventCallback('foo', PoolInterface::EVENT_DISPOSE, $callbacks[PoolInterface::EVENT_DISPOSE][0]);

// 3. Define all callbacks in one method call
$pool->addEventsCallbacks('foo', $callback);

$pool->addEventCallback('foo', PoolInterface::EVENT_GET, function($instance) { echo 'a'; });
$pool->addEventCallback('foo', PoolInterface::EVENT_GET, function($instance) { echo 'b'; });

$pool->get('foo'); // will echo 'a' and 'b'

class Foo {
    public function bar() { echo 'blablabla'; }
}

$counter = 0;
$pool = new Pool\Pool();
$pool->set('foo', function() { return new Foo(); }, [
    PoolInterface::EVENT_GET => [function($instance) { $instance->bar(); }],
    PoolInterface::EVENT_DISPOSE => [function($instance) use (&$counter) { $counter++; }]
]);

$foo = $pool->get('foo'); // $foo->bar() is called

$pool->dispose($foo); // the counter is incremented