Container.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <?php
  2. namespace Symfony\Component\DependencyInjection;
  3. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  4. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  5. use Symfony\Component\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. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  50. */
  51. class Container implements ContainerInterface, \ArrayAccess
  52. {
  53. protected $parameterBag;
  54. protected $services;
  55. /**
  56. * Constructor.
  57. *
  58. * @param ParameterBagInterface $parameterBag A ParameterBagInterface instance
  59. */
  60. public function __construct(ParameterBagInterface $parameterBag = null)
  61. {
  62. $this->parameterBag = null === $parameterBag ? new ParameterBag() : $parameterBag;
  63. $this->services = array();
  64. $this->set('service_container', $this);
  65. }
  66. /**
  67. * Freezes the container.
  68. *
  69. * This method does two things:
  70. *
  71. * * Parameter values are resolved;
  72. * * The parameter bag is freezed.
  73. */
  74. public function freeze()
  75. {
  76. $this->parameterBag->resolve();
  77. $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
  78. }
  79. /**
  80. * Returns true if the container parameter bag are frozen.
  81. *
  82. * @return Boolean true if the container parameter bag are frozen, false otherwise
  83. */
  84. public function isFrozen()
  85. {
  86. return $this->parameterBag instanceof FrozenParameterBag;
  87. }
  88. /**
  89. * Gets the service container parameter bag.
  90. *
  91. * @return ParameterBagInterface A ParameterBagInterface instance
  92. */
  93. public function getParameterBag()
  94. {
  95. return $this->parameterBag;
  96. }
  97. /**
  98. * Gets a parameter.
  99. *
  100. * @param string $name The parameter name
  101. *
  102. * @return mixed The parameter value
  103. *
  104. * @throws \InvalidArgumentException if the parameter is not defined
  105. */
  106. public function getParameter($name)
  107. {
  108. return $this->parameterBag->get($name);
  109. }
  110. /**
  111. * Checks if a parameter exists.
  112. *
  113. * @param string $name The parameter name
  114. *
  115. * @return boolean The presence of parameter in container
  116. */
  117. public function hasParameter($name)
  118. {
  119. return $this->parameterBag->has($name);
  120. }
  121. /**
  122. * Sets a parameter.
  123. *
  124. * @param string $name The parameter name
  125. * @param mixed $parameters The parameter value
  126. */
  127. public function setParameter($name, $value)
  128. {
  129. $this->parameterBag->set($name, $value);
  130. }
  131. /**
  132. * Sets a service.
  133. *
  134. * @param string $id The service identifier
  135. * @param object $service The service instance
  136. */
  137. public function set($id, $service)
  138. {
  139. $this->services[$id] = $service;
  140. }
  141. /**
  142. * Returns true if the given service is defined.
  143. *
  144. * @param string $id The service identifier
  145. *
  146. * @return Boolean true if the service is defined, false otherwise
  147. */
  148. public function has($id)
  149. {
  150. return isset($this->services[$id]) || method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_')).'Service');
  151. }
  152. /**
  153. * Gets a service.
  154. *
  155. * If a service is both defined through a set() method and
  156. * with a set*Service() method, the former has always precedence.
  157. *
  158. * @param string $id The service identifier
  159. * @param int $invalidBehavior The behavior when the service does not exist
  160. *
  161. * @return object The associated service
  162. *
  163. * @throws \InvalidArgumentException if the service is not defined
  164. *
  165. * @see Reference
  166. */
  167. public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
  168. {
  169. if (!is_string($id)) {
  170. throw new \InvalidArgumentException(sprintf('A service id should be a string (%s given).', str_replace("\n", '', var_export($id, true))));
  171. }
  172. if (isset($this->services[$id])) {
  173. return $this->services[$id];
  174. }
  175. if (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  176. return $this->$method();
  177. }
  178. if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  179. throw new \InvalidArgumentException(sprintf('The service "%s" does not exist.', $id));
  180. }
  181. }
  182. /**
  183. * Gets all service ids.
  184. *
  185. * @return array An array of all defined service ids
  186. */
  187. public function getServiceIds()
  188. {
  189. $ids = array();
  190. $r = new \ReflectionClass($this);
  191. foreach ($r->getMethods() as $method) {
  192. if (preg_match('/^get(.+)Service$/', $name = $method->getName(), $match)) {
  193. $ids[] = self::underscore($match[1]);
  194. }
  195. }
  196. return array_merge($ids, array_keys($this->services));
  197. }
  198. /**
  199. * Returns true if the service id is defined (implements the ArrayAccess interface).
  200. *
  201. * @param string $id The service id
  202. *
  203. * @return Boolean true if the service id is defined, false otherwise
  204. */
  205. public function offsetExists($id)
  206. {
  207. return $this->has($id);
  208. }
  209. /**
  210. * Gets a service by id (implements the ArrayAccess interface).
  211. *
  212. * @param string $id The service id
  213. *
  214. * @return mixed The parameter value
  215. */
  216. public function offsetGet($id)
  217. {
  218. return $this->get($id);
  219. }
  220. /**
  221. * Sets a service (implements the ArrayAccess interface).
  222. *
  223. * @param string $id The service id
  224. * @param object $value The service
  225. */
  226. public function offsetSet($id, $value)
  227. {
  228. $this->set($id, $value);
  229. }
  230. /**
  231. * Removes a service (implements the ArrayAccess interface).
  232. *
  233. * @param string $id The service id
  234. */
  235. public function offsetUnset($id)
  236. {
  237. throw new \LogicException(sprintf('You can\'t unset a service (%s).', $id));
  238. }
  239. /**
  240. * Catches unknown methods.
  241. *
  242. * @param string $method The called method name
  243. * @param array $arguments The method arguments
  244. *
  245. * @return mixed
  246. *
  247. * @throws \BadMethodCallException When calling to an undefined method
  248. */
  249. public function __call($method, $arguments)
  250. {
  251. if (!preg_match('/^get(.+)Service$/', $method, $match)) {
  252. throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
  253. }
  254. return $this->get(self::underscore($match[1]));
  255. }
  256. static public function camelize($id)
  257. {
  258. return preg_replace(array('/(?:^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\1')", "'_'.strtoupper('\\1')"), $id);
  259. }
  260. static public function underscore($id)
  261. {
  262. return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
  263. }
  264. }