Container.php 9.1 KB

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