Container.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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\InactiveScopeException;
  12. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  13. use Symfony\Component\DependencyInjection\Exception\LogicException;
  14. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  15. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  16. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  17. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  18. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  19. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  20. /**
  21. * Container is a dependency injection container.
  22. *
  23. * It gives access to object instances (services).
  24. *
  25. * Services and parameters are simple key/pair stores.
  26. *
  27. * Parameter and service keys are case insensitive.
  28. *
  29. * A service can also be defined by creating a method named
  30. * getXXXService(), where XXX is the camelized version of the id:
  31. *
  32. * * request -> getRequestService()
  33. * * mysql_session_storage -> getMysqlSessionStorageService()
  34. * * symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()
  35. *
  36. * The container can have three possible behaviors when a service does not exist:
  37. *
  38. * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
  39. * * NULL_ON_INVALID_REFERENCE: Returns null
  40. * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
  41. * (for instance, ignore a setter if the service does not exist)
  42. *
  43. * @author Fabien Potencier <fabien@symfony.com>
  44. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  45. */
  46. class Container implements IntrospectableContainerInterface, ResettableContainerInterface
  47. {
  48. protected $parameterBag;
  49. protected $services = array();
  50. protected $methodMap = array();
  51. protected $aliases = array();
  52. protected $scopes = array();
  53. protected $scopeChildren = array();
  54. protected $scopedServices = array();
  55. protected $scopeStacks = array();
  56. protected $loading = array();
  57. private $underscoreMap = array('_' => '', '.' => '_', '\\' => '_');
  58. public function __construct(ParameterBagInterface $parameterBag = null)
  59. {
  60. $this->parameterBag = $parameterBag ?: new ParameterBag();
  61. }
  62. /**
  63. * Compiles the container.
  64. *
  65. * This method does two things:
  66. *
  67. * * Parameter values are resolved;
  68. * * The parameter bag is frozen.
  69. */
  70. public function compile()
  71. {
  72. $this->parameterBag->resolve();
  73. $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
  74. }
  75. /**
  76. * Returns true if the container parameter bag are frozen.
  77. *
  78. * @return bool true if the container parameter bag are frozen, false otherwise
  79. */
  80. public function isFrozen()
  81. {
  82. return $this->parameterBag instanceof FrozenParameterBag;
  83. }
  84. /**
  85. * Gets the service container parameter bag.
  86. *
  87. * @return ParameterBagInterface A ParameterBagInterface instance
  88. */
  89. public function getParameterBag()
  90. {
  91. return $this->parameterBag;
  92. }
  93. /**
  94. * Gets a parameter.
  95. *
  96. * @param string $name The parameter name
  97. *
  98. * @return mixed The parameter value
  99. *
  100. * @throws InvalidArgumentException if the parameter is not defined
  101. */
  102. public function getParameter($name)
  103. {
  104. return $this->parameterBag->get($name);
  105. }
  106. /**
  107. * Checks if a parameter exists.
  108. *
  109. * @param string $name The parameter name
  110. *
  111. * @return bool The presence of parameter in container
  112. */
  113. public function hasParameter($name)
  114. {
  115. return $this->parameterBag->has($name);
  116. }
  117. /**
  118. * Sets a parameter.
  119. *
  120. * @param string $name The parameter name
  121. * @param mixed $value The parameter value
  122. */
  123. public function setParameter($name, $value)
  124. {
  125. $this->parameterBag->set($name, $value);
  126. }
  127. /**
  128. * Sets a service.
  129. *
  130. * Setting a service to null resets the service: has() returns false and get()
  131. * behaves in the same way as if the service was never created.
  132. *
  133. * Note: The $scope parameter is deprecated since version 2.8 and will be removed in 3.0.
  134. *
  135. * @param string $id The service identifier
  136. * @param object $service The service instance
  137. * @param string $scope The scope of the service
  138. *
  139. * @throws RuntimeException When trying to set a service in an inactive scope
  140. * @throws InvalidArgumentException When trying to set a service in the prototype scope
  141. */
  142. public function set($id, $service, $scope = self::SCOPE_CONTAINER)
  143. {
  144. if (!\in_array($scope, array('container', 'request')) || ('request' === $scope && 'request' !== $id)) {
  145. @trigger_error('The concept of container scopes is deprecated since Symfony 2.8 and will be removed in 3.0. Omit the third parameter.', E_USER_DEPRECATED);
  146. }
  147. if (self::SCOPE_PROTOTYPE === $scope) {
  148. throw new InvalidArgumentException(sprintf('You cannot set service "%s" of scope "prototype".', $id));
  149. }
  150. $id = strtolower($id);
  151. if ('service_container' === $id) {
  152. // BC: 'service_container' is no longer a self-reference but always
  153. // $this, so ignore this call.
  154. // @todo Throw InvalidArgumentException in next major release.
  155. return;
  156. }
  157. if (self::SCOPE_CONTAINER !== $scope) {
  158. if (!isset($this->scopedServices[$scope])) {
  159. throw new RuntimeException(sprintf('You cannot set service "%s" of inactive scope.', $id));
  160. }
  161. $this->scopedServices[$scope][$id] = $service;
  162. }
  163. if (isset($this->aliases[$id])) {
  164. unset($this->aliases[$id]);
  165. }
  166. $this->services[$id] = $service;
  167. if (method_exists($this, $method = 'synchronize'.strtr($id, $this->underscoreMap).'Service')) {
  168. $this->$method();
  169. }
  170. if (null === $service) {
  171. if (self::SCOPE_CONTAINER !== $scope) {
  172. unset($this->scopedServices[$scope][$id]);
  173. }
  174. unset($this->services[$id]);
  175. }
  176. }
  177. /**
  178. * Returns true if the given service is defined.
  179. *
  180. * @param string $id The service identifier
  181. *
  182. * @return bool true if the service is defined, false otherwise
  183. */
  184. public function has($id)
  185. {
  186. for ($i = 2;;) {
  187. if ('service_container' === $id
  188. || isset($this->aliases[$id])
  189. || isset($this->services[$id])
  190. || array_key_exists($id, $this->services)
  191. ) {
  192. return true;
  193. }
  194. if (--$i && $id !== $lcId = strtolower($id)) {
  195. $id = $lcId;
  196. } else {
  197. return method_exists($this, 'get'.strtr($id, $this->underscoreMap).'Service');
  198. }
  199. }
  200. }
  201. /**
  202. * Gets a service.
  203. *
  204. * If a service is defined both through a set() method and
  205. * with a get{$id}Service() method, the former has always precedence.
  206. *
  207. * @param string $id The service identifier
  208. * @param int $invalidBehavior The behavior when the service does not exist
  209. *
  210. * @return object The associated service
  211. *
  212. * @throws ServiceCircularReferenceException When a circular reference is detected
  213. * @throws ServiceNotFoundException When the service is not defined
  214. * @throws \Exception if an exception has been thrown when the service has been resolved
  215. *
  216. * @see Reference
  217. */
  218. public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
  219. {
  220. // Attempt to retrieve the service by checking first aliases then
  221. // available services. Service IDs are case insensitive, however since
  222. // this method can be called thousands of times during a request, avoid
  223. // calling strtolower() unless necessary.
  224. for ($i = 2;;) {
  225. if (isset($this->aliases[$id])) {
  226. $id = $this->aliases[$id];
  227. }
  228. // Re-use shared service instance if it exists.
  229. if (isset($this->services[$id]) || array_key_exists($id, $this->services)) {
  230. return $this->services[$id];
  231. }
  232. if ('service_container' === $id) {
  233. return $this;
  234. }
  235. if (isset($this->loading[$id])) {
  236. throw new ServiceCircularReferenceException($id, array_keys($this->loading));
  237. }
  238. if (isset($this->methodMap[$id])) {
  239. $method = $this->methodMap[$id];
  240. } elseif (--$i && $id !== $lcId = strtolower($id)) {
  241. $id = $lcId;
  242. continue;
  243. } elseif (method_exists($this, $method = 'get'.strtr($id, $this->underscoreMap).'Service')) {
  244. // $method is set to the right value, proceed
  245. } else {
  246. if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  247. if (!$id) {
  248. throw new ServiceNotFoundException($id);
  249. }
  250. $alternatives = array();
  251. foreach ($this->getServiceIds() as $knownId) {
  252. $lev = levenshtein($id, $knownId);
  253. if ($lev <= \strlen($id) / 3 || false !== strpos($knownId, $id)) {
  254. $alternatives[] = $knownId;
  255. }
  256. }
  257. throw new ServiceNotFoundException($id, null, null, $alternatives);
  258. }
  259. return;
  260. }
  261. $this->loading[$id] = true;
  262. try {
  263. $service = $this->$method();
  264. } catch (\Exception $e) {
  265. unset($this->loading[$id]);
  266. unset($this->services[$id]);
  267. if ($e instanceof InactiveScopeException && self::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
  268. return;
  269. }
  270. throw $e;
  271. } catch (\Throwable $e) {
  272. unset($this->loading[$id]);
  273. unset($this->services[$id]);
  274. throw $e;
  275. }
  276. unset($this->loading[$id]);
  277. return $service;
  278. }
  279. }
  280. /**
  281. * Returns true if the given service has actually been initialized.
  282. *
  283. * @param string $id The service identifier
  284. *
  285. * @return bool true if service has already been initialized, false otherwise
  286. */
  287. public function initialized($id)
  288. {
  289. $id = strtolower($id);
  290. if (isset($this->aliases[$id])) {
  291. $id = $this->aliases[$id];
  292. }
  293. if ('service_container' === $id) {
  294. // BC: 'service_container' was a synthetic service previously.
  295. // @todo Change to false in next major release.
  296. return true;
  297. }
  298. return isset($this->services[$id]) || array_key_exists($id, $this->services);
  299. }
  300. /**
  301. * {@inheritdoc}
  302. */
  303. public function reset()
  304. {
  305. if (!empty($this->scopedServices)) {
  306. throw new LogicException('Resetting the container is not allowed when a scope is active.');
  307. }
  308. $this->services = array();
  309. }
  310. /**
  311. * Gets all service ids.
  312. *
  313. * @return array An array of all defined service ids
  314. */
  315. public function getServiceIds()
  316. {
  317. $ids = array();
  318. foreach (get_class_methods($this) as $method) {
  319. if (preg_match('/^get(.+)Service$/', $method, $match)) {
  320. $ids[] = self::underscore($match[1]);
  321. }
  322. }
  323. $ids[] = 'service_container';
  324. return array_unique(array_merge($ids, array_keys($this->services)));
  325. }
  326. /**
  327. * This is called when you enter a scope.
  328. *
  329. * @param string $name
  330. *
  331. * @throws RuntimeException When the parent scope is inactive
  332. * @throws InvalidArgumentException When the scope does not exist
  333. *
  334. * @deprecated since version 2.8, to be removed in 3.0.
  335. */
  336. public function enterScope($name)
  337. {
  338. if ('request' !== $name) {
  339. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
  340. }
  341. if (!isset($this->scopes[$name])) {
  342. throw new InvalidArgumentException(sprintf('The scope "%s" does not exist.', $name));
  343. }
  344. if (self::SCOPE_CONTAINER !== $this->scopes[$name] && !isset($this->scopedServices[$this->scopes[$name]])) {
  345. throw new RuntimeException(sprintf('The parent scope "%s" must be active when entering this scope.', $this->scopes[$name]));
  346. }
  347. // check if a scope of this name is already active, if so we need to
  348. // remove all services of this scope, and those of any of its child
  349. // scopes from the global services map
  350. if (isset($this->scopedServices[$name])) {
  351. $services = array($this->services, $name => $this->scopedServices[$name]);
  352. unset($this->scopedServices[$name]);
  353. foreach ($this->scopeChildren[$name] as $child) {
  354. if (isset($this->scopedServices[$child])) {
  355. $services[$child] = $this->scopedServices[$child];
  356. unset($this->scopedServices[$child]);
  357. }
  358. }
  359. // update global map
  360. $this->services = \call_user_func_array('array_diff_key', $services);
  361. array_shift($services);
  362. // add stack entry for this scope so we can restore the removed services later
  363. if (!isset($this->scopeStacks[$name])) {
  364. $this->scopeStacks[$name] = new \SplStack();
  365. }
  366. $this->scopeStacks[$name]->push($services);
  367. }
  368. $this->scopedServices[$name] = array();
  369. }
  370. /**
  371. * This is called to leave the current scope, and move back to the parent
  372. * scope.
  373. *
  374. * @param string $name The name of the scope to leave
  375. *
  376. * @throws InvalidArgumentException if the scope is not active
  377. *
  378. * @deprecated since version 2.8, to be removed in 3.0.
  379. */
  380. public function leaveScope($name)
  381. {
  382. if ('request' !== $name) {
  383. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
  384. }
  385. if (!isset($this->scopedServices[$name])) {
  386. throw new InvalidArgumentException(sprintf('The scope "%s" is not active.', $name));
  387. }
  388. // remove all services of this scope, or any of its child scopes from
  389. // the global service map
  390. $services = array($this->services, $this->scopedServices[$name]);
  391. unset($this->scopedServices[$name]);
  392. foreach ($this->scopeChildren[$name] as $child) {
  393. if (isset($this->scopedServices[$child])) {
  394. $services[] = $this->scopedServices[$child];
  395. unset($this->scopedServices[$child]);
  396. }
  397. }
  398. // update global map
  399. $this->services = \call_user_func_array('array_diff_key', $services);
  400. // check if we need to restore services of a previous scope of this type
  401. if (isset($this->scopeStacks[$name]) && \count($this->scopeStacks[$name]) > 0) {
  402. $services = $this->scopeStacks[$name]->pop();
  403. $this->scopedServices += $services;
  404. if ($this->scopeStacks[$name]->isEmpty()) {
  405. unset($this->scopeStacks[$name]);
  406. }
  407. foreach ($services as $array) {
  408. foreach ($array as $id => $service) {
  409. $this->set($id, $service, $name);
  410. }
  411. }
  412. }
  413. }
  414. /**
  415. * Adds a scope to the container.
  416. *
  417. * @throws InvalidArgumentException
  418. *
  419. * @deprecated since version 2.8, to be removed in 3.0.
  420. */
  421. public function addScope(ScopeInterface $scope)
  422. {
  423. $name = $scope->getName();
  424. $parentScope = $scope->getParentName();
  425. if ('request' !== $name) {
  426. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
  427. }
  428. if (self::SCOPE_CONTAINER === $name || self::SCOPE_PROTOTYPE === $name) {
  429. throw new InvalidArgumentException(sprintf('The scope "%s" is reserved.', $name));
  430. }
  431. if (isset($this->scopes[$name])) {
  432. throw new InvalidArgumentException(sprintf('A scope with name "%s" already exists.', $name));
  433. }
  434. if (self::SCOPE_CONTAINER !== $parentScope && !isset($this->scopes[$parentScope])) {
  435. throw new InvalidArgumentException(sprintf('The parent scope "%s" does not exist, or is invalid.', $parentScope));
  436. }
  437. $this->scopes[$name] = $parentScope;
  438. $this->scopeChildren[$name] = array();
  439. // normalize the child relations
  440. while (self::SCOPE_CONTAINER !== $parentScope) {
  441. $this->scopeChildren[$parentScope][] = $name;
  442. $parentScope = $this->scopes[$parentScope];
  443. }
  444. }
  445. /**
  446. * Returns whether this container has a certain scope.
  447. *
  448. * @param string $name The name of the scope
  449. *
  450. * @return bool
  451. *
  452. * @deprecated since version 2.8, to be removed in 3.0.
  453. */
  454. public function hasScope($name)
  455. {
  456. if ('request' !== $name) {
  457. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
  458. }
  459. return isset($this->scopes[$name]);
  460. }
  461. /**
  462. * Returns whether this scope is currently active.
  463. *
  464. * This does not actually check if the passed scope actually exists.
  465. *
  466. * @param string $name
  467. *
  468. * @return bool
  469. *
  470. * @deprecated since version 2.8, to be removed in 3.0.
  471. */
  472. public function isScopeActive($name)
  473. {
  474. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
  475. return isset($this->scopedServices[$name]);
  476. }
  477. /**
  478. * Camelizes a string.
  479. *
  480. * @param string $id A string to camelize
  481. *
  482. * @return string The camelized string
  483. */
  484. public static function camelize($id)
  485. {
  486. return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));
  487. }
  488. /**
  489. * A string to underscore.
  490. *
  491. * @param string $id The string to underscore
  492. *
  493. * @return string The underscored string
  494. */
  495. public static function underscore($id)
  496. {
  497. return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id)));
  498. }
  499. private function __clone()
  500. {
  501. }
  502. }