public
Last active

dependency injection in php/codeigniter

  • Download Gist
dependency_inject.php
PHP
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
<?php
class BASE_Model extends CI_Model
{
/**
* inject_class - load class using dependency injection
*
* @access public
* @param string $path
* @param string $class
* @param string $func
* @param string $method
**/
public function inject_class($path, $class, $func, $method)
{
// load_class is a function located in system/core/common.php on line 123
$obj = load_class($class, $path, NULL);
return $obj->$func();
}
}
 
// lets say this is instantiated by a user controller when a new user is made
class User_model extends BASE_Model
{
public function create()
{
echo 'create a new user';
$request = $this->inject_class('path/to/models', 'Logger_model', 'log');
echo $request;
}
}
 
class Logger_model extends BASE_Model
{
public function log()
{
return 'Logged';
}
}

this would be better defined as object collaboration/delegation and not dependency injection. DI would have the controller passing an instance of a Model to a Model

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.