Container.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. namespace Symfony\Components\DependencyInjection;
  3. use Symfony\Components\DependencyInjection\ParameterBag\ParameterBagInterface;
  4. use Symfony\Components\DependencyInjection\ParameterBag\ParameterBag;
  5. use Symfony\Components\DependencyInjection\ParameterBag\FrozenParameterBag;
  6. /*
  7. * This file is part of the Symfony framework.
  8. *
  9. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  10. *
  11. * This source file is subject to the MIT license that is bundled
  12. * with this source code in the file LICENSE.
  13. */
  14. /**
  15. * Container is a dependency injection container.
  16. *
  17. * It gives access to object instances (services).
  18. *
  19. * Services and parameters are simple key/pair stores.
  20. *
  21. * Parameters keys are case insensitive.
  22. *
  23. * A service id can contain lowercased letters, digits, underscores, and dots.
  24. * Underscores are used to separate words, and dots to group services
  25. * under namespaces:
  26. *
  27. * <ul>
  28. * <li>request</li>
  29. * <li>mysql_session_storage</li>
  30. * <li>symfony.mysql_session_storage</li>
  31. * </ul>
  32. *
  33. * A service can also be defined by creating a method named
  34. * getXXXService(), where XXX is the camelized version of the id:
  35. *
  36. * <ul>
  37. * <li>request -> getRequestService()</li>
  38. * <li>mysql_session_storage -> getMysqlSessionStorageService()</li>
  39. * <li>symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()</li>
  40. * </ul>
  41. *
  42. * The container can have three possible behaviors when a service does not exist:
  43. *
  44. * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
  45. * * NULL_ON_INVALID_REFERENCE: Returns null
  46. * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
  47. * (for instance, ignore a setter if the service does not exist)
  48. *
  49. * @package Symfony
  50. * @subpackage Components_DependencyInjection
  51. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  52. */
  53. class Container implements ContainerInterface, \ArrayAccess
  54. {
  55. protected $parameterBag;
  56. protected $services;
  57. /**
  58. * Constructor.
  59. *
  60. * @param Symfony\Components\DependencyInjection\ParameterBagInterface $parameterBag A ParameterBagInterface instance
  61. */
  62. public function __construct(ParameterBagInterface $parameterBag = null)
  63. {
  64. $this->parameterBag = null === $parameterBag ? new ParameterBag() : $parameterBag;
  65. $this->services = array();
  66. $this->set('service_container', $this);
  67. }
  68. /**
  69. * Freezes the container.
  70. *
  71. * This method does two things:
  72. *
  73. * * Parameter values are resolved;
  74. * * The parameter bag is freezed.
  75. */
  76. public function freeze()
  77. {
  78. $this->parameterBag->resolve();
  79. $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
  80. }
  81. /**
  82. * Returns true if the container parameter bag are frozen.
  83. *
  84. * @return Boolean true if the container parameter bag are frozen, false otherwise
  85. */
  86. public function isFrozen()
  87. {
  88. return $this->parameterBag instanceof FrozenParameterBag;
  89. }
  90. /**
  91. * Gets the service container parameter bag.
  92. *
  93. * @return Symfony\Components\DependencyInjection\ParameterBag\ParameterBagInterface A ParameterBagInterface instance
  94. */
  95. public function getParameterBag()
  96. {
  97. return $this->parameterBag;
  98. }
  99. /**
  100. * Gets a parameter.
  101. *
  102. * @param string $name The parameter name
  103. *
  104. * @return mixed The parameter value
  105. *
  106. * @throws \InvalidArgumentException if the parameter is not defined
  107. */
  108. public function getParameter($name)
  109. {
  110. return $this->parameterBag->get($name);
  111. }
  112. /**
  113. * Sets a parameter.
  114. *
  115. * @param string $name The parameter name
  116. * @param mixed $parameters The parameter value
  117. */
  118. public function setParameter($name, $value)
  119. {
  120. $this->parameterBag->set($name, $value);
  121. }
  122. /**
  123. * Sets a service.
  124. *
  125. * @param string $id The service identifier
  126. * @param object $service The service instance
  127. */
  128. public function set($id, $service)
  129. {
  130. $this->services[$id] = $service;
  131. }
  132. /**
  133. * Returns true if the given service is defined.
  134. *
  135. * @param string $id The service identifier
  136. *
  137. * @return Boolean true if the service is defined, false otherwise
  138. */
  139. public function has($id)
  140. {
  141. return isset($this->services[$id]) || method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_')).'Service');
  142. }
  143. /**
  144. * Gets a service.
  145. *
  146. * If a service is both defined through a set() method and
  147. * with a set*Service() method, the former has always precedence.
  148. *
  149. * @param string $id The service identifier
  150. * @param int $invalidBehavior The behavior when the service does not exist
  151. *
  152. * @return object The associated service
  153. *
  154. * @throws \InvalidArgumentException if the service is not defined
  155. *
  156. * @see Reference
  157. */
  158. public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
  159. {
  160. if (!is_string($id)) {
  161. throw new \InvalidArgumentException(sprintf('A service id should be a string (%s given).', str_replace("\n", '', var_export($id, true))));
  162. }
  163. if (isset($this->services[$id])) {
  164. return $this->services[$id];
  165. }
  166. if (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  167. return $this->$method();
  168. }
  169. if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  170. throw new \InvalidArgumentException(sprintf('The service "%s" does not exist.', $id));
  171. } else {
  172. return null;
  173. }
  174. }
  175. /**
  176. * Gets all service ids.
  177. *
  178. * @return array An array of all defined service ids
  179. */
  180. public function getServiceIds()
  181. {
  182. $ids = array();
  183. $r = new \ReflectionClass($this);
  184. foreach ($r->getMethods() as $method) {
  185. if (preg_match('/^get(.+)Service$/', $name = $method->getName(), $match)) {
  186. $ids[] = self::underscore($match[1]);
  187. }
  188. }
  189. return array_merge($ids, array_keys($this->services));
  190. }
  191. /**
  192. * Returns true if the service id is defined (implements the ArrayAccess interface).
  193. *
  194. * @param string $id The service id
  195. *
  196. * @return Boolean true if the service id is defined, false otherwise
  197. */
  198. public function offsetExists($id)
  199. {
  200. return $this->has($id);
  201. }
  202. /**
  203. * Gets a service by id (implements the ArrayAccess interface).
  204. *
  205. * @param string $id The service id
  206. *
  207. * @return mixed The parameter value
  208. */
  209. public function offsetGet($id)
  210. {
  211. return $this->get($id);
  212. }
  213. /**
  214. * Sets a service (implements the ArrayAccess interface).
  215. *
  216. * @param string $id The service id
  217. * @param object $value The service
  218. */
  219. public function offsetSet($id, $value)
  220. {
  221. $this->set($id, $value);
  222. }
  223. /**
  224. * Removes a service (implements the ArrayAccess interface).
  225. *
  226. * @param string $id The service id
  227. */
  228. public function offsetUnset($id)
  229. {
  230. throw new \LogicException(sprintf('You can\'t unset a service (%s).', $id));
  231. }
  232. /**
  233. * Catches unknown methods.
  234. *
  235. * @param string $method The called method name
  236. * @param array $arguments The method arguments
  237. *
  238. * @return mixed
  239. *
  240. * @throws \BadMethodCallException When calling to an undefined method
  241. */
  242. public function __call($method, $arguments)
  243. {
  244. if (!preg_match('/^get(.+)Service$/', $method, $match)) {
  245. throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
  246. }
  247. return $this->get(self::underscore($match[1]));
  248. }
  249. static public function camelize($id)
  250. {
  251. return preg_replace(array('/(^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $id);
  252. }
  253. static public function underscore($id)
  254. {
  255. return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
  256. }
  257. }