After build methods support in di52

Small but useful addition to the PHP 5.2 compatible dependency injection container.

Not all objects are built equal

The DI52 package is born out of my need and will to use a dependency injection container in my WordPress projects.
The minimum supported version is still PHP 5.2 and DI containers for PHP 5.3 and above are abundant.
Mocking an interface similar to what Pimple and the Laravel Container offer di52 supports an array access API and a method based API.
The latter did lack, up to this moment, a way to bind an object along with its accessory initialization methods.

Code example

I could have a Cache object that’s in charge of handling the cache and is supposed to “prime” it before use; I’d want that priming to happen as late as possible and only if needed.
In a PHP 5.3 or above enviroment that would be easy:

$container = new tad_DI52_Container();

$container->singleton('CacheInterface', function(){
  $cache = new Cache();
  $cache->prime();
  $cache->listen();

  return $cache;
});

// later in the code...

// the cache is built and primed here
$cache = $container->make('CacheInterface');
$val = $cache->get('some-key');

All this quiet standard in the context of DI containers but not so in the context of DI52; in a PHP 5.2 environment the closest one could get to that, without access to the Cache class, was to create a lazy extension of the class:

class LazyCache extends Cache {

    protected $primed = false; 

    publid function prime(){
        if(!$this->primed){
            $this->prime();
            $this->listen();
            $this->primed = true;
        }
    }

    public function get($key) {
        $this->prime();

        return $this->get($key);
    }

    public function set($key, $value){
        $this->prime();

        return $this->set($key,$value);
    }
}

to then register it in the container:

$container = new tad_DI52_Container();

$container->singleton('CacheInterface', 'LazyCache');

// later in the code...

// the cache is built here
$cache = $container->make('CacheInterface');

// and primed here
$val = $cache->get('some-key');

This seems advantegeous, but the if(!$this->primed) check will run, and will have to be put in place, in each method.

Run something after, please

Version 1.4.1 of DI52 tries to solve the problem allowing the contextual registration of additional methods to run after the object is built with very little overhead:

$container = new tad_DI52_Container();

$container->singleton('CacheInterface', 'Cache', array('prime', 'listen'));

// later in the code...

// the cache is built and primed here
$cache = $container->make('CacheInterface');
$val = $cache->get('some-key');

Thus eliminating the need for a class extension (more code to maintain) and to fill in the gap of the missing closures support in PHP 5.2.