Could there be a best practice / way to load a dynamic class in php?

Having a main class in which any code has access, can some kind of code load the dynamic class in a similar but best practice way?

candidate code:

static public function __callStatic($mtd,$arg){ // using spl_autoload_register() $class = '\\framework\\libs\\'.$mtd; $inst = new $class($arg); } 

Syntax:

 main::dinamicu($data); 
+7
source share
2 answers

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.

+2
source

My two cents:

Since you mentioned “best practices”, suggesting that you are talking about something similar to the Locator Service pattern (which is your main::dinamicu($data); ), some will argue that this is not a good model when the assumption is test-based development. Instead of a service locator, a dependency injection container is best.

In a way, similar to the factory class, the container will take care of class instances. To get a clear idea of ​​examples of how to create objects, see the Example below (Symfony Service Container):

http://fabien.potencier.org/article/13/introduction-to-the-symfony-service-container

(The symfony service container, in the braid of accepting the dependency injection container, is still used as a service locator on the controllers, as in the code you posted)

0
source

All Articles