Dependency injection containers in WordPress 04

Adding post construction method calls to the PHP 5.2 dependency injection container.

A possibility

Anonymous, naydoer constructors, are a tool I continuously use in PHP to ease TDD: the simple truth behind it is that instance mocking is easier and circular references are easily avoided. An example of an empty and dumb constructor is this

class SomeClass{}

it’s implicit and

$c = new SomeClass();

will just return an instance of SomeClass. That class might have, though, some attributes to set using methods like this

class SomeClass{
    protected $p1;
    protected $p2;

    public function setP1($value){
        $this->p1 = $value;
    }

    public function setP2($value){
        $this->p2 = $value;
    }
}

and using the dependency injection container like this

$c = new tad_DI52_Container();
$c->set_ctor('someClass' , 'SomeClass');
$i = $c->make('someClass');

print($i->p1); // null
print($i->p2); // null

Will leave the instance half baked. I could call the methods on the instance later on like this

$c = new tad_DI52_Container();
$c->set_ctor('someClass' , 'SomeClass');
$i = $c->make('someClass');

$i->setP1('foo');
$i->setP2(23);

that would defeat the purpose of a dependency injection container and its convenience.

First smartness

I’ve pushed a modification to the GitHub repository that allows methods to be called on the object after it’s been instantiated; for the following class

class SomeClass {

    public $dependency;
    public $string;
    public $int;

    public static function makeOne( Dependency $dependency ) {
        $instance = new self();
        $instance->dependency = $dependency;

        return $instance;
    }

    public function setDependency( Dependency $dependency ) {
        $this->dependency = $dependency;
    }

    public function setString( $string ) {
        $this->string = $string;
    }

    public function setInt( $int ) {
        $this->int = $int;
    }
} 

I can register the constructors and get instances of the objects like this

$this->sut->set_ctor( 'dependency', 'Dependency' );
$this->sut->set_var( 'string', 'foo' );
$this->sut->set_var( 'int', 23 );

// using the __construct method
$this->sut->set_ctor( 'some class construct', 'SomeClass')
    ->setDependency( '@dependency' )
    ->setString( '#string' )
    ->setInt( '#int' );

// using the makeOne method
$args = array('@dependency')
$this->sut->set_ctor( 'some class make one', 'SomeClass::makeOne', $args )
    ->setString( '#string' )
    ->setInt( '#int' );

// both return a set up instance of SomeClass
$i1 = $this->sut->make( 'some class construct' );
$i2 = $this->sut->make( 'some class make one' ); 

Next

I will add some guessing capabilities to the container to instantiate data objects.

I appreciate your input