PageRenderTime 49ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/DependencyInjection/Container.php

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