Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Trying to Learn IoC and dependency injection
<?
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 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, 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.