secret
Last active

Trying to Learn IoC and dependency injection

  • Download Gist
Inheritance IoC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
<?
 
class mysqliWrapper extends mysqli
{
function __construct()
{
/*
This won't work since the parent constructor is generic,
and I want it constructed with the specific parameters defined by the IoC
*/
parent::__construct();
 
/*
This won't work you're prohibited from setting the $this variable,
*/
$this = IoC::resolve('mysqli');
}
 
function __construct($mysqli)
{
$this->dependency1 = $mysqli->dependency1;
/*
This requires me to know all the dependencies for my parent class
*/
}
}
 
IoC::register('mysqliWrapper', function(){
/*
Doing it this way requires me to repeat code, and know all
the dependencies of the parent class, which I'm trying to avoid.
*/
$mysqliWrapper = new mysqliWrapper();
$mysqliWrapper->dependency = '...';
 
 
$mysqli = IoC::resolve('mysqli');
});
Registering A Mysqli Object
1 2 3 4 5 6 7 8 9 10 11
<?
//registering mysqli with the credentials specific to this project in the IoC
IoC::register('mysqli', function(){
$host = 'localhost';
$username = 'ProjectName_User';
$password = 'somePassword';
$database = 'Project_Database';
 
return new mysqli($host, $username, $password, $database);
 
});
The IoC Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
//The IoC Class, Copied From Here: http://net.tutsplus.com/tutorials/php/dependency-injection-huh/
 
class IoC {
/**
* @var PDO The connection to the database
*/
protected static $registry = array();
/**
* Add a new resolver to the registry array.
* @param string $name The id
* @param object $resolve Closure that creates instance
* @return void
*/
public static function register($name, Closure $resolve)
{
static::$registry[$name] = $resolve;
}
 
/**
* Create the instance
* @param string $name The id
* @return mixed
*/
public static function resolve($name)
{
if ( static::registered($name) )
{
$name = static::$registry[$name];
return $name();
}
else
{
throw new Exception('Nothing registered with that name.');
}
}
/**
* Determine whether the id is registered
* @param string $name The id
* @return bool Whether to id exists or not
*/
public static function registered($name)
{
return array_key_exists($name, static::$registry);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.