Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

class

load

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);
like image 650
John Smith Optional Avatar asked Aug 09 '12 17:08

John Smith Optional


1 Answers

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.

like image 127
JvdBerg Avatar answered Nov 14 '22 09:11

JvdBerg