FuseLogic - Lite version of Dependency Injection


/ Published in: PHP
Save to your folder(s)

Very usefull lite dependency injection for PHP5.
Usage:

di exends fuselogic_container()
{
function __construct()
{
parant::__construct(__FILE__);
}
}

safe this to the folder with others class with name "class.class_name.php'
then you can do like bellow

$di = new di();
$c1 = $di->class_x; //singleton
$c2 = $di->class_x; //singleton
$c3 = $di->class_x(); //not singleton


Copy this code and paste it in your HTML
  1. //PHP5 only
  2. class fuselogic_container
  3. {
  4. var $__x = array();
  5.  
  6. function __construct($path = null)
  7. {
  8. static $instances = array();
  9. $class_name = strtolower(get_class($this));
  10. if(!isset($instances[$class_name]))
  11. {
  12. $instances[$class_name] = $this;
  13. }
  14. foreach(get_class_vars($class_name) as $var => $value)
  15. {
  16. $this->$var = &$instances[$class_name]->$var;
  17. }
  18. $this->__path = isset($path)?$path:getcwd();
  19. }
  20.  
  21. function __get($name)
  22. {
  23. $lowercase = strtolower($name);
  24. if(isset($this->__x[$lowercase]))
  25. {
  26. return $this->__x[$lowercase];
  27. }else
  28. {
  29. $this->__x[$lowercase] = $this->$name();
  30. $instance = &$this->__x[$lowercase];
  31. return $instance;
  32. }
  33. }
  34.  
  35. function __call($name,$var)
  36. {
  37. if(class_exists($name))
  38. {
  39. if(isset($var[0]))
  40. {
  41. return new $name($var[0]);
  42. }else
  43. {
  44. return new $name();
  45. }
  46. }else
  47. {
  48. $this->_start();
  49. if(@include_once('class.'.$name.'.php'))
  50. {
  51. return new $name();
  52. }
  53. $this->_end();
  54. }
  55. }
  56.  
  57. function _start()
  58. {
  59. $this->__path_back = getcwd();
  60. chdir($this->__path);
  61. }
  62.  
  63. function _end()
  64. {
  65. chdir($this->__path_back);
  66. }
  67.  
  68. function __set($name,$val)
  69. {
  70. $this->__x[$name] = $val;
  71. }
  72.  
  73. function __isset($name)
  74. {
  75. $name = strtolower($name);
  76. if(isset($this->__x[$name]))
  77. {
  78. return true;
  79. }elseif(method_exists($this,$name))
  80. {
  81. return true;
  82. }else return false;
  83. }
  84. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.