I use the inversion control container for this situation.
I start with the facade class:
class IoC { private static $container; public static function Initialize ( IContainer $Container ) { self::$container = $Container; } public static function Resolve( $type, array $parameters = array() ) { return self::$container->Resolve( $type, $parameters ); } }
Then, im my bootstrapper, I initialize the facade class with the Injection Dependency container:
$container = new Container(); $container->Register( 'Logger', function() { return new Logger('somefile.log'); } ); IoC::Initialize ( $container );
Then somewhere in my code, when I want to get an object:
$log = IoC::Resolve( 'Logger' );
Using this approach, I am completely free in how I implement the container for dependency injection. I can change it in any way without breaking the code in my application.
I can test the container without statics by simply creating a new container.
Jvdberg
source share