Container.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. *
  4. * Cube Framework $Id$ 1CNyrzajXKNbvkn3LEv+xIlN6UgXQKp/pezSHYn/KQQ=
  5. *
  6. * @link http://codecu.be/framework
  7. * @copyright Copyright (c) 2014 CodeCube SRL
  8. * @license http://codecu.be/framework/license Commercial License
  9. *
  10. * @version 1.0
  11. */
  12. /**
  13. * dependency injection container
  14. */
  15. namespace Cube\Di;
  16. class Container implements ContainerInterface
  17. {
  18. /**
  19. *
  20. * objects container
  21. *
  22. * @var array
  23. */
  24. protected $_services = array();
  25. /**
  26. *
  27. * add a new service to the container
  28. *
  29. * @param string $name the name of the service to be saved in the container
  30. * @param mixed $service the service that will be saved
  31. * @return \Cube\Di\Container
  32. * @throws \InvalidArgumentException
  33. */
  34. public function set($name, $service)
  35. {
  36. if (!is_object($service) && !is_string($service)) {
  37. throw new \InvalidArgumentException("Only objects or strings can be registered with the container.");
  38. }
  39. if (!in_array($service, $this->_services, true)) {
  40. $this->_services[$name] = $service;
  41. }
  42. return $this;
  43. }
  44. /**
  45. *
  46. * get a service from the container
  47. *
  48. * @param string $name
  49. * @param array $params
  50. * @return mixed
  51. * @throws \RuntimeException
  52. */
  53. public function get($name, array $params = array())
  54. {
  55. if (!isset($this->_services[$name])) {
  56. throw new \RuntimeException(sprintf("The service '%s' has not been registered with the container.", $name));
  57. }
  58. $service = $this->_services[$name];
  59. return !$service instanceof \Closure ? $service : call_user_func_array($service, $params);
  60. }
  61. /**
  62. *
  63. * check if a service has been saved in the container
  64. *
  65. * @param string $name
  66. * @return bool
  67. */
  68. public function has($name)
  69. {
  70. return isset($this->_services[$name]);
  71. }
  72. /**
  73. *
  74. * remove a service from the container
  75. *
  76. * @param string $name
  77. * @return \Cube\Di\Container
  78. */
  79. public function remove($name)
  80. {
  81. if (isset($this->_services[$name])) {
  82. unset($this->_services[$name]);
  83. }
  84. return $this;
  85. }
  86. /**
  87. *
  88. * clear the container
  89. */
  90. public function clear()
  91. {
  92. $this->_services = array();
  93. }
  94. }