Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Created October 31, 2012 00:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayleedev/3984020 to your computer and use it in GitHub Desktop.
Save bayleedev/3984020 to your computer and use it in GitHub Desktop.
Dep Injection
<?php
interface iGame {
public function start();
public function end();
public function move();
}
class tictactoe implements iGame {
public function start() {
return 'begin!' . PHP_EOL;
}
public function end() {
return 'game over!' . PHP_EOL;
}
public function move() {
return 'moving...' . PHP_EOL;
}
}
class advancedTicTacToe {
public function __construct(tictactoe $game) {
$this->game = $game;
}
public function __call($method, $params) {
if(in_array($method, array('start', 'end', 'move'))) {
return $this->game->$method();
}
throw new BadMethodCallException('Method ' . $method . ' does not exist');
}
}
class library {
public static $instances;
/**
* Will attempt to create a class and give it all it's required parameters
*
* @param string $className
* @return object
*/
public function create($className) {
// Generate params
$params = array();
if(method_exists($className, '__construct')) {
// Get params
$function = new ReflectionMethod($className, '__construct');
foreach ($function->getParameters() as $param) {
$name = $param->getName();
if(!isset(self::$instances[$name])) {
// Create if it doesn't already exist
self::$instances[$name] = $this->create($param->getClass()->getName());
}
$params[$name] =& self::$instances[$name];
}
// Create class
$ref = new \ReflectionClass($className);
return $ref->newInstanceArgs($params);
} else {
// No constructor
return new $className();
}
}
}
$lib = new library();
$snickers = $lib->create('advancedTicTacToe');
echo $snickers->start(); // begin!
echo $snickers->move(); // moving...
echo $snickers->end(); // game over!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment