John Smith Optional
John Smith Optional

Reputation: 129

Can exist a best practice/way to load dynamic class at php?

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);

Upvotes: 7

Views: 420

Answers (2)

JvdBerg
JvdBerg

Reputation: 21856

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.

Upvotes: 2

Keyne Viana
Keyne Viana

Reputation: 6202

My two cents:

Since you have mentioned "best practices", assuming that you are talking about something similar to the Service Locator Pattern (which is your main::dinamicu($data);), some would argue that this is not a good pattern when the assumption is test driven development. Instead of the service locator, the best would be a dependency injection container.

In some ways similar to a factory class, the container will take care of the classes instantiations. To get a clear idea about and see examples on how to deal with the objects creation, see the example below (Symfony Service Container):

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

(The symfony service container, in spit of the adoption of a dependency injection container, it's still used as a service locator on the controllers, as in the code you have posted)

Upvotes: 0

Related Questions