Container.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  12. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  13. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  14. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  15. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  16. /**
  17. * Container is a dependency injection container.
  18. *
  19. * It gives access to object instances (services).
  20. *
  21. * Services and parameters are simple key/pair stores.
  22. *
  23. * Parameter and service keys are case insensitive.
  24. *
  25. * A service id can contain lowercased letters, digits, underscores, and dots.
  26. * Underscores are used to separate words, and dots to group services
  27. * under namespaces:
  28. *
  29. * <ul>
  30. * <li>request</li>
  31. * <li>mysql_session_storage</li>
  32. * <li>symfony.mysql_session_storage</li>
  33. * </ul>
  34. *
  35. * A service can also be defined by creating a method named
  36. * getXXXService(), where XXX is the camelized version of the id:
  37. *
  38. * <ul>
  39. * <li>request -> getRequestService()</li>
  40. * <li>mysql_session_storage -> getMysqlSessionStorageService()</li>
  41. * <li>symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()</li>
  42. * </ul>
  43. *
  44. * The container can have three possible behaviors when a service does not exist:
  45. *
  46. * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
  47. * * NULL_ON_INVALID_REFERENCE: Returns null
  48. * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
  49. * (for instance, ignore a setter if the service does not exist)
  50. *
  51. * @author Fabien Potencier <fabien@symfony.com>
  52. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  53. */
  54. class Container implements ContainerInterface
  55. {
  56. protected $parameterBag;
  57. protected $services;
  58. protected $scopes;
  59. protected $scopeChildren;
  60. protected $scopedServices;
  61. protected $scopeStacks;
  62. protected $loading = array();
  63. /**
  64. * Constructor.
  65. *
  66. * @param ParameterBagInterface $parameterBag A ParameterBagInterface instance
  67. */
  68. public function __construct(ParameterBagInterface $parameterBag = null)
  69. {
  70. $this->parameterBag = null === $parameterBag ? new ParameterBag() : $parameterBag;
  71. $this->services = array();
  72. $this->scopes = array();
  73. $this->scopeChildren = array();
  74. $this->scopedServices = array();
  75. $this->scopeStacks = array();
  76. $this->set('service_container', $this);
  77. }
  78. /**
  79. * Compiles the container.
  80. *
  81. * This method does two things:
  82. *
  83. * * Parameter values are resolved;
  84. * * The parameter bag is frozen.
  85. */
  86. public function compile()
  87. {
  88. $this->parameterBag->resolve();
  89. $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
  90. }
  91. /**
  92. * Returns true if the container parameter bag are frozen.
  93. *
  94. * @return Boolean true if the container parameter bag are frozen, false otherwise
  95. */
  96. public function isFrozen()
  97. {
  98. return $this->parameterBag instanceof FrozenParameterBag;
  99. }
  100. /**
  101. * Gets the service container parameter bag.
  102. *
  103. * @return ParameterBagInterface A ParameterBagInterface instance
  104. */
  105. public function getParameterBag()
  106. {
  107. return $this->parameterBag;
  108. }
  109. /**
  110. * Gets a parameter.
  111. *
  112. * @param string $name The parameter name
  113. *
  114. * @return mixed The parameter value
  115. *
  116. * @throws \InvalidArgumentException if the parameter is not defined
  117. */
  118. public function getParameter($name)
  119. {
  120. return $this->parameterBag->get($name);
  121. }
  122. /**
  123. * Checks if a parameter exists.
  124. *
  125. * @param string $name The parameter name
  126. *
  127. * @return Boolean The presence of parameter in container
  128. */
  129. public function hasParameter($name)
  130. {
  131. return $this->parameterBag->has($name);
  132. }
  133. /**
  134. * Sets a parameter.
  135. *
  136. * @param string $name The parameter name
  137. * @param mixed $value The parameter value
  138. */
  139. public function setParameter($name, $value)
  140. {
  141. $this->parameterBag->set($name, $value);
  142. }
  143. /**
  144. * Sets a service.
  145. *
  146. * @param string $id The service identifier
  147. * @param object $service The service instance
  148. * @param string $scope The scope of the service
  149. */
  150. public function set($id, $service, $scope = self::SCOPE_CONTAINER)
  151. {
  152. if (self::SCOPE_PROTOTYPE === $scope) {
  153. throw new \InvalidArgumentException('You cannot set services of scope "prototype".');
  154. }
  155. $id = strtolower($id);
  156. if (self::SCOPE_CONTAINER !== $scope) {
  157. if (!isset($this->scopedServices[$scope])) {
  158. throw new \RuntimeException('You cannot set services of inactive scopes.');
  159. }
  160. $this->scopedServices[$scope][$id] = $service;
  161. }
  162. $this->services[$id] = $service;
  163. }
  164. /**
  165. * Returns true if the given service is defined.
  166. *
  167. * @param string $id The service identifier
  168. *
  169. * @return Boolean true if the service is defined, false otherwise
  170. */
  171. public function has($id)
  172. {
  173. $id = strtolower($id);
  174. return isset($this->services[$id]) || method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_')).'Service');
  175. }
  176. /**
  177. * Gets a service.
  178. *
  179. * If a service is both defined through a set() method and
  180. * with a set*Service() method, the former has always precedence.
  181. *
  182. * @param string $id The service identifier
  183. * @param integer $invalidBehavior The behavior when the service does not exist
  184. *
  185. * @return object The associated service
  186. *
  187. * @throws \InvalidArgumentException if the service is not defined
  188. *
  189. * @see Reference
  190. */
  191. public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
  192. {
  193. $id = strtolower($id);
  194. if (isset($this->services[$id])) {
  195. return $this->services[$id];
  196. }
  197. if (isset($this->loading[$id])) {
  198. throw new ServiceCircularReferenceException($id, array_keys($this->loading));
  199. }
  200. if (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  201. $this->loading[$id] = true;
  202. try {
  203. $service = $this->$method();
  204. } catch (\Exception $e) {
  205. unset($this->loading[$id]);
  206. throw $e;
  207. }
  208. unset($this->loading[$id]);
  209. return $service;
  210. }
  211. if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  212. throw new ServiceNotFoundException($id);
  213. }
  214. }
  215. /**
  216. * Gets all service ids.
  217. *
  218. * @return array An array of all defined service ids
  219. */
  220. public function getServiceIds()
  221. {
  222. $ids = array();
  223. $r = new \ReflectionClass($this);
  224. foreach ($r->getMethods() as $method) {
  225. if (preg_match('/^get(.+)Service$/', $method->getName(), $match)) {
  226. $ids[] = self::underscore($match[1]);
  227. }
  228. }
  229. return array_unique(array_merge($ids, array_keys($this->services)));
  230. }
  231. /**
  232. * This is called when you enter a scope
  233. *
  234. * @param string $name
  235. * @return void
  236. */
  237. public function enterScope($name)
  238. {
  239. if (!isset($this->scopes[$name])) {
  240. throw new \InvalidArgumentException(sprintf('The scope "%s" does not exist.', $name));
  241. }
  242. if (self::SCOPE_CONTAINER !== $this->scopes[$name] && !isset($this->scopedServices[$this->scopes[$name]])) {
  243. throw new \RuntimeException(sprintf('The parent scope "%s" must be active when entering this scope.', $this->scopes[$name]));
  244. }
  245. // check if a scope of this name is already active, if so we need to
  246. // remove all services of this scope, and those of any of its child
  247. // scopes from the global services map
  248. if (isset($this->scopedServices[$name])) {
  249. $services = array($this->services, $name => $this->scopedServices[$name]);
  250. unset($this->scopedServices[$name]);
  251. foreach ($this->scopeChildren[$name] as $child) {
  252. $services[$child] = $this->scopedServices[$child];
  253. unset($this->scopedServices[$child]);
  254. }
  255. // update global map
  256. $this->services = call_user_func_array('array_diff_key', $services);
  257. array_shift($services);
  258. // add stack entry for this scope so we can restore the removed services later
  259. if (!isset($this->scopeStacks[$name])) {
  260. $this->scopeStacks[$name] = new \SplStack();
  261. }
  262. $this->scopeStacks[$name]->push($services);
  263. }
  264. $this->scopedServices[$name] = array();
  265. }
  266. /**
  267. * Returns the current stacked service scope for the given name
  268. *
  269. * @param string $name The service name
  270. * @return array The service scope
  271. */
  272. public function getCurrentScopedStack($name)
  273. {
  274. if (!isset($this->scopeStacks[$name]) || 0 === $this->scopeStacks[$name]->count()) {
  275. return null;
  276. }
  277. return $this->scopeStacks[$name]->top();
  278. }
  279. /**
  280. * This is called to leave the current scope, and move back to the parent
  281. * scope.
  282. *
  283. * @param string $name The name of the scope to leave
  284. * @return void
  285. * @throws \InvalidArgumentException if the scope is not active
  286. */
  287. public function leaveScope($name)
  288. {
  289. if (!isset($this->scopedServices[$name])) {
  290. throw new \InvalidArgumentException(sprintf('The scope "%s" is not active.', $name));
  291. }
  292. // remove all services of this scope, or any of its child scopes from
  293. // the global service map
  294. $services = array($this->services, $this->scopedServices[$name]);
  295. unset($this->scopedServices[$name]);
  296. foreach ($this->scopeChildren[$name] as $child) {
  297. if (!isset($this->scopedServices[$child])) {
  298. continue;
  299. }
  300. $services[] = $this->scopedServices[$child];
  301. unset($this->scopedServices[$child]);
  302. }
  303. $this->services = call_user_func_array('array_diff_key', $services);
  304. // check if we need to restore services of a previous scope of this type
  305. if (isset($this->scopeStacks[$name]) && count($this->scopeStacks[$name]) > 0) {
  306. $services = $this->scopeStacks[$name]->pop();
  307. $this->scopedServices += $services;
  308. array_unshift($services, $this->services);
  309. $this->services = call_user_func_array('array_merge', $services);
  310. }
  311. }
  312. /**
  313. * Adds a scope to the container.
  314. *
  315. * @param ScopeInterface $scope
  316. * @return void
  317. */
  318. public function addScope(ScopeInterface $scope)
  319. {
  320. $name = $scope->getName();
  321. $parentScope = $scope->getParentName();
  322. if (self::SCOPE_CONTAINER === $name || self::SCOPE_PROTOTYPE === $name) {
  323. throw new \InvalidArgumentException(sprintf('The scope "%s" is reserved.', $name));
  324. }
  325. if (isset($this->scopes[$name])) {
  326. throw new \InvalidArgumentException(sprintf('A scope with name "%s" already exists.', $name));
  327. }
  328. if (self::SCOPE_CONTAINER !== $parentScope && !isset($this->scopes[$parentScope])) {
  329. throw new \InvalidArgumentException(sprintf('The parent scope "%s" does not exist, or is invalid.', $parentScope));
  330. }
  331. $this->scopes[$name] = $parentScope;
  332. $this->scopeChildren[$name] = array();
  333. // normalize the child relations
  334. while ($parentScope !== self::SCOPE_CONTAINER) {
  335. $this->scopeChildren[$parentScope][] = $name;
  336. $parentScope = $this->scopes[$parentScope];
  337. }
  338. }
  339. /**
  340. * Returns whether this container has a certain scope
  341. *
  342. * @param string $name The name of the scope
  343. * @return Boolean
  344. */
  345. public function hasScope($name)
  346. {
  347. return isset($this->scopes[$name]);
  348. }
  349. /**
  350. * Returns whether this scope is currently active
  351. *
  352. * This does not actually check if the passed scope actually exists.
  353. *
  354. * @param string $name
  355. * @return Boolean
  356. */
  357. public function isScopeActive($name)
  358. {
  359. return isset($this->scopedServices[$name]);
  360. }
  361. /**
  362. * Camelizes a string.
  363. *
  364. * @param string $id A string to camelize
  365. * @return string The camelized string
  366. */
  367. static public function camelize($id)
  368. {
  369. return preg_replace(array('/(?:^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\1')", "'_'.strtoupper('\\1')"), $id);
  370. }
  371. /**
  372. * A string to underscore.
  373. *
  374. * @param string $id The string to underscore
  375. * @return string The underscored string
  376. */
  377. static public function underscore($id)
  378. {
  379. return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
  380. }
  381. }