Container.php 19 KB

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