Skip to content

Instantly share code, notes, and snippets.

@andredublin
Created August 22, 2012 18:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andredublin/3428071 to your computer and use it in GitHub Desktop.
Save andredublin/3428071 to your computer and use it in GitHub Desktop.
dependency injection in php/codeigniter
<?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';
}
}
@andredublin
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment