Container.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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;
  66. protected $methodMap;
  67. protected $aliases;
  68. protected $scopes;
  69. protected $scopeChildren;
  70. protected $scopedServices;
  71. protected $scopeStacks;
  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 = null === $parameterBag ? new ParameterBag() : $parameterBag;
  83. $this->services = array();
  84. $this->aliases = array();
  85. $this->scopes = array();
  86. $this->scopeChildren = array();
  87. $this->scopedServices = array();
  88. $this->scopeStacks = array();
  89. $this->set('service_container', $this);
  90. }
  91. /**
  92. * Compiles the container.
  93. *
  94. * This method does two things:
  95. *
  96. * * Parameter values are resolved;
  97. * * The parameter bag is frozen.
  98. *
  99. * @api
  100. */
  101. public function compile()
  102. {
  103. $this->parameterBag->resolve();
  104. $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
  105. }
  106. /**
  107. * Returns true if the container parameter bag are frozen.
  108. *
  109. * @return Boolean true if the container parameter bag are frozen, false otherwise
  110. *
  111. * @api
  112. */
  113. public function isFrozen()
  114. {
  115. return $this->parameterBag instanceof FrozenParameterBag;
  116. }
  117. /**
  118. * Gets the service container parameter bag.
  119. *
  120. * @return ParameterBagInterface A ParameterBagInterface instance
  121. *
  122. * @api
  123. */
  124. public function getParameterBag()
  125. {
  126. return $this->parameterBag;
  127. }
  128. /**
  129. * Gets a parameter.
  130. *
  131. * @param string $name The parameter name
  132. *
  133. * @return mixed The parameter value
  134. *
  135. * @throws InvalidArgumentException if the parameter is not defined
  136. *
  137. * @api
  138. */
  139. public function getParameter($name)
  140. {
  141. return $this->parameterBag->get($name);
  142. }
  143. /**
  144. * Checks if a parameter exists.
  145. *
  146. * @param string $name The parameter name
  147. *
  148. * @return Boolean The presence of parameter in container
  149. *
  150. * @api
  151. */
  152. public function hasParameter($name)
  153. {
  154. return $this->parameterBag->has($name);
  155. }
  156. /**
  157. * Sets a parameter.
  158. *
  159. * @param string $name The parameter name
  160. * @param mixed $value The parameter value
  161. *
  162. * @api
  163. */
  164. public function setParameter($name, $value)
  165. {
  166. $this->parameterBag->set($name, $value);
  167. }
  168. /**
  169. * Sets a service.
  170. *
  171. * Setting a service to null resets the service: has() returns false and get()
  172. * behaves in the same way as if the service was never created.
  173. *
  174. * @param string $id The service identifier
  175. * @param object $service The service instance
  176. * @param string $scope The scope of the service
  177. *
  178. * @throws RuntimeException When trying to set a service in an inactive scope
  179. * @throws InvalidArgumentException When trying to set a service in the prototype scope
  180. *
  181. * @api
  182. */
  183. public function set($id, $service, $scope = self::SCOPE_CONTAINER)
  184. {
  185. if (self::SCOPE_PROTOTYPE === $scope) {
  186. throw new InvalidArgumentException(sprintf('You cannot set service "%s" of scope "prototype".', $id));
  187. }
  188. $id = strtolower($id);
  189. if (self::SCOPE_CONTAINER !== $scope) {
  190. if (!isset($this->scopedServices[$scope])) {
  191. throw new RuntimeException(sprintf('You cannot set service "%s" of inactive scope.', $id));
  192. }
  193. $this->scopedServices[$scope][$id] = $service;
  194. }
  195. $this->services[$id] = $service;
  196. if (method_exists($this, $method = 'synchronize'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  197. $this->$method();
  198. }
  199. if (self::SCOPE_CONTAINER !== $scope && null === $service) {
  200. unset($this->scopedServices[$scope][$id]);
  201. }
  202. if (null === $service) {
  203. unset($this->services[$id]);
  204. }
  205. }
  206. /**
  207. * Returns true if the given service is defined.
  208. *
  209. * @param string $id The service identifier
  210. *
  211. * @return Boolean true if the service is defined, false otherwise
  212. *
  213. * @api
  214. */
  215. public function has($id)
  216. {
  217. $id = strtolower($id);
  218. return array_key_exists($id, $this->services)
  219. || array_key_exists($id, $this->aliases)
  220. || method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')
  221. ;
  222. }
  223. /**
  224. * Gets a service.
  225. *
  226. * If a service is defined both through a set() method and
  227. * with a get{$id}Service() method, the former has always precedence.
  228. *
  229. * @param string $id The service identifier
  230. * @param integer $invalidBehavior The behavior when the service does not exist
  231. *
  232. * @return object The associated service
  233. *
  234. * @throws InvalidArgumentException if the service is not defined
  235. * @throws ServiceCircularReferenceException When a circular reference is detected
  236. * @throws ServiceNotFoundException When the service is not defined
  237. *
  238. * @see Reference
  239. *
  240. * @api
  241. */
  242. public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
  243. {
  244. $id = strtolower($id);
  245. // resolve aliases
  246. if (isset($this->aliases[$id])) {
  247. $id = $this->aliases[$id];
  248. }
  249. // re-use shared service instance if it exists
  250. if (array_key_exists($id, $this->services)) {
  251. return $this->services[$id];
  252. }
  253. if (isset($this->loading[$id])) {
  254. throw new ServiceCircularReferenceException($id, array_keys($this->loading));
  255. }
  256. if (isset($this->methodMap[$id])) {
  257. $method = $this->methodMap[$id];
  258. } elseif (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  259. // $method is set to the right value, proceed
  260. } else {
  261. if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  262. if (!$id) {
  263. throw new ServiceNotFoundException($id);
  264. }
  265. $alternatives = array();
  266. foreach (array_keys($this->services) as $key) {
  267. $lev = levenshtein($id, $key);
  268. if ($lev <= strlen($id) / 3 || false !== strpos($key, $id)) {
  269. $alternatives[] = $key;
  270. }
  271. }
  272. throw new ServiceNotFoundException($id, null, null, $alternatives);
  273. }
  274. return null;
  275. }
  276. $this->loading[$id] = true;
  277. try {
  278. $service = $this->$method();
  279. } catch (\Exception $e) {
  280. unset($this->loading[$id]);
  281. if (array_key_exists($id, $this->services)) {
  282. unset($this->services[$id]);
  283. }
  284. if ($e instanceof InactiveScopeException && self::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
  285. return null;
  286. }
  287. throw $e;
  288. }
  289. unset($this->loading[$id]);
  290. return $service;
  291. }
  292. /**
  293. * Returns true if the given service has actually been initialized
  294. *
  295. * @param string $id The service identifier
  296. *
  297. * @return Boolean true if service has already been initialized, false otherwise
  298. */
  299. public function initialized($id)
  300. {
  301. return array_key_exists(strtolower($id), $this->services);
  302. }
  303. /**
  304. * Gets all service ids.
  305. *
  306. * @return array An array of all defined service ids
  307. */
  308. public function getServiceIds()
  309. {
  310. $ids = array();
  311. $r = new \ReflectionClass($this);
  312. foreach ($r->getMethods() as $method) {
  313. if (preg_match('/^get(.+)Service$/', $method->name, $match)) {
  314. $ids[] = self::underscore($match[1]);
  315. }
  316. }
  317. return array_unique(array_merge($ids, array_keys($this->services)));
  318. }
  319. /**
  320. * This is called when you enter a scope
  321. *
  322. * @param string $name
  323. *
  324. * @throws RuntimeException When the parent scope is inactive
  325. * @throws InvalidArgumentException When the scope does not exist
  326. *
  327. * @api
  328. */
  329. public function enterScope($name)
  330. {
  331. if (!isset($this->scopes[$name])) {
  332. throw new InvalidArgumentException(sprintf('The scope "%s" does not exist.', $name));
  333. }
  334. if (self::SCOPE_CONTAINER !== $this->scopes[$name] && !isset($this->scopedServices[$this->scopes[$name]])) {
  335. throw new RuntimeException(sprintf('The parent scope "%s" must be active when entering this scope.', $this->scopes[$name]));
  336. }
  337. // check if a scope of this name is already active, if so we need to
  338. // remove all services of this scope, and those of any of its child
  339. // scopes from the global services map
  340. if (isset($this->scopedServices[$name])) {
  341. $services = array($this->services, $name => $this->scopedServices[$name]);
  342. unset($this->scopedServices[$name]);
  343. foreach ($this->scopeChildren[$name] as $child) {
  344. if (isset($this->scopedServices[$child])) {
  345. $services[$child] = $this->scopedServices[$child];
  346. unset($this->scopedServices[$child]);
  347. }
  348. }
  349. // update global map
  350. $this->services = call_user_func_array('array_diff_key', $services);
  351. array_shift($services);
  352. // add stack entry for this scope so we can restore the removed services later
  353. if (!isset($this->scopeStacks[$name])) {
  354. $this->scopeStacks[$name] = new \SplStack();
  355. }
  356. $this->scopeStacks[$name]->push($services);
  357. }
  358. $this->scopedServices[$name] = array();
  359. }
  360. /**
  361. * This is called to leave the current scope, and move back to the parent
  362. * scope.
  363. *
  364. * @param string $name The name of the scope to leave
  365. *
  366. * @throws InvalidArgumentException if the scope is not active
  367. *
  368. * @api
  369. */
  370. public function leaveScope($name)
  371. {
  372. if (!isset($this->scopedServices[$name])) {
  373. throw new InvalidArgumentException(sprintf('The scope "%s" is not active.', $name));
  374. }
  375. // remove all services of this scope, or any of its child scopes from
  376. // the global service map
  377. $services = array($this->services, $this->scopedServices[$name]);
  378. unset($this->scopedServices[$name]);
  379. foreach ($this->scopeChildren[$name] as $child) {
  380. if (!isset($this->scopedServices[$child])) {
  381. continue;
  382. }
  383. $services[] = $this->scopedServices[$child];
  384. unset($this->scopedServices[$child]);
  385. }
  386. $this->services = call_user_func_array('array_diff_key', $services);
  387. // check if we need to restore services of a previous scope of this type
  388. if (isset($this->scopeStacks[$name]) && count($this->scopeStacks[$name]) > 0) {
  389. $services = $this->scopeStacks[$name]->pop();
  390. $this->scopedServices += $services;
  391. foreach ($services as $array) {
  392. foreach ($array as $id => $service) {
  393. $this->set($id, $service, $name);
  394. }
  395. }
  396. }
  397. }
  398. /**
  399. * Adds a scope to the container.
  400. *
  401. * @param ScopeInterface $scope
  402. *
  403. * @throws InvalidArgumentException
  404. *
  405. * @api
  406. */
  407. public function addScope(ScopeInterface $scope)
  408. {
  409. $name = $scope->getName();
  410. $parentScope = $scope->getParentName();
  411. if (self::SCOPE_CONTAINER === $name || self::SCOPE_PROTOTYPE === $name) {
  412. throw new InvalidArgumentException(sprintf('The scope "%s" is reserved.', $name));
  413. }
  414. if (isset($this->scopes[$name])) {
  415. throw new InvalidArgumentException(sprintf('A scope with name "%s" already exists.', $name));
  416. }
  417. if (self::SCOPE_CONTAINER !== $parentScope && !isset($this->scopes[$parentScope])) {
  418. throw new InvalidArgumentException(sprintf('The parent scope "%s" does not exist, or is invalid.', $parentScope));
  419. }
  420. $this->scopes[$name] = $parentScope;
  421. $this->scopeChildren[$name] = array();
  422. // normalize the child relations
  423. while ($parentScope !== self::SCOPE_CONTAINER) {
  424. $this->scopeChildren[$parentScope][] = $name;
  425. $parentScope = $this->scopes[$parentScope];
  426. }
  427. }
  428. /**
  429. * Returns whether this container has a certain scope
  430. *
  431. * @param string $name The name of the scope
  432. *
  433. * @return Boolean
  434. *
  435. * @api
  436. */
  437. public function hasScope($name)
  438. {
  439. return isset($this->scopes[$name]);
  440. }
  441. /**
  442. * Returns whether this scope is currently active
  443. *
  444. * This does not actually check if the passed scope actually exists.
  445. *
  446. * @param string $name
  447. *
  448. * @return Boolean
  449. *
  450. * @api
  451. */
  452. public function isScopeActive($name)
  453. {
  454. return isset($this->scopedServices[$name]);
  455. }
  456. /**
  457. * Camelizes a string.
  458. *
  459. * @param string $id A string to camelize
  460. *
  461. * @return string The camelized string
  462. */
  463. public static function camelize($id)
  464. {
  465. return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ '))), array(' ' => ''));
  466. }
  467. /**
  468. * A string to underscore.
  469. *
  470. * @param string $id The string to underscore
  471. *
  472. * @return string The underscored string
  473. */
  474. public static function underscore($id)
  475. {
  476. return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
  477. }
  478. }