Having a main class where any code has access, can some code similar, but with a best practice to load dynamic class?
candidate code:
static public function __callStatic($mtd,$arg){
// using spl_autoload_register()
$class = '\\framework\\libs\\'.$mtd;
$inst = new $class($arg);
}
syntax:
main::dinamicu($data);
I use a Inversion of Control container for this situation.
I start with a 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 a Dependency Injection 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 a object:
$log = IoC::Resolve( 'Logger' );
By using this approach I am completely free in how I implement my dependency injection container. I can change it in any way, without breaking code in my application.
I can test the container with no statics al all, just by creating a new Container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With