4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection
;
14 use Symfony\Component\DependencyInjection\Exception\InactiveScopeException
;
15 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
;
16 use Symfony\Component\DependencyInjection\Exception\LogicException
;
17 use Symfony\Component\DependencyInjection\Exception\RuntimeException
;
18 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
;
19 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
;
20 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface
;
21 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag
;
22 use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag
;
25 * Container is a dependency injection container.
27 * It gives access to object instances (services).
29 * Services and parameters are simple key/pair stores.
31 * Parameter and service keys are case insensitive.
33 * A service can also be defined by creating a method named
34 * getXXXService(), where XXX is the camelized version of the id:
37 * <li>request -> getRequestService()</li>
38 * <li>mysql_session_storage -> getMysqlSessionStorageService()</li>
39 * <li>symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()</li>
42 * The container can have three possible behaviors when a service does not exist:
44 * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
45 * * NULL_ON_INVALID_REFERENCE: Returns null
46 * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
47 * (for instance, ignore a setter if the service does not exist)
49 * @author Fabien Potencier <fabien@symfony.com>
50 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
52 class Container
implements IntrospectableContainerInterface
, ResettableContainerInterface
54 protected $parameterBag;
55 protected $services = array();
56 protected $methodMap = array();
57 protected $aliases = array();
58 protected $scopes = array();
59 protected $scopeChildren = array();
60 protected $scopedServices = array();
61 protected $scopeStacks = array();
62 protected $loading = array();
64 private $underscoreMap = array('_' => '', '.' => '_', '\\' => '_');
66 public function __construct(ParameterBagInterface
$parameterBag = null)
68 $this->parameterBag
= $parameterBag ?
: new ParameterBag();
72 * Compiles the container.
74 * This method does two things:
76 * * Parameter values are resolved;
77 * * The parameter bag is frozen.
79 public function compile()
81 $this->parameterBag
->resolve();
83 $this->parameterBag
= new FrozenParameterBag($this->parameterBag
->all());
87 * Returns true if the container parameter bag are frozen.
89 * @return bool true if the container parameter bag are frozen, false otherwise
91 public function isFrozen()
93 return $this->parameterBag
instanceof FrozenParameterBag
;
97 * Gets the service container parameter bag.
99 * @return ParameterBagInterface A ParameterBagInterface instance
101 public function getParameterBag()
103 return $this->parameterBag
;
109 * @param string $name The parameter name
111 * @return mixed The parameter value
113 * @throws InvalidArgumentException if the parameter is not defined
115 public function getParameter($name)
117 return $this->parameterBag
->get($name);
121 * Checks if a parameter exists.
123 * @param string $name The parameter name
125 * @return bool The presence of parameter in container
127 public function hasParameter($name)
129 return $this->parameterBag
->has($name);
135 * @param string $name The parameter name
136 * @param mixed $value The parameter value
138 public function setParameter($name, $value)
140 $this->parameterBag
->set($name, $value);
146 * Setting a service to null resets the service: has() returns false and get()
147 * behaves in the same way as if the service was never created.
149 * Note: The $scope parameter is deprecated since version 2.8 and will be removed in 3.0.
151 * @param string $id The service identifier
152 * @param object $service The service instance
153 * @param string $scope The scope of the service
155 * @throws RuntimeException When trying to set a service in an inactive scope
156 * @throws InvalidArgumentException When trying to set a service in the prototype scope
158 public function set($id, $service, $scope = self
::SCOPE_CONTAINER
)
160 if (!in_array($scope, array('container', 'request')) ||
('request' === $scope && 'request' !== $id)) {
161 @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
);
164 if (self
::SCOPE_PROTOTYPE
=== $scope) {
165 throw new InvalidArgumentException(sprintf('You cannot set service "%s" of scope "prototype".', $id));
168 $id = strtolower($id);
170 if ('service_container' === $id) {
171 // BC: 'service_container' is no longer a self-reference but always
172 // $this, so ignore this call.
173 // @todo Throw InvalidArgumentException in next major release.
176 if (self
::SCOPE_CONTAINER
!== $scope) {
177 if (!isset($this->scopedServices
[$scope])) {
178 throw new RuntimeException(sprintf('You cannot set service "%s" of inactive scope.', $id));
181 $this->scopedServices
[$scope][$id] = $service;
184 if (isset($this->aliases
[$id])) {
185 unset($this->aliases
[$id]);
188 $this->services
[$id] = $service;
190 if (method_exists($this, $method = 'synchronize'.strtr($id, $this->underscoreMap
).'Service')) {
194 if (null === $service) {
195 if (self
::SCOPE_CONTAINER
!== $scope) {
196 unset($this->scopedServices
[$scope][$id]);
199 unset($this->services
[$id]);
204 * Returns true if the given service is defined.
206 * @param string $id The service identifier
208 * @return bool true if the service is defined, false otherwise
210 public function has($id)
213 if ('service_container' === $id
214 ||
isset($this->aliases
[$id])
215 ||
isset($this->services
[$id])
216 ||
array_key_exists($id, $this->services
)
220 if (--$i && $id !== $lcId = strtolower($id)) {
223 return method_exists($this, 'get'.strtr($id, $this->underscoreMap
).'Service');
231 * If a service is defined both through a set() method and
232 * with a get{$id}Service() method, the former has always precedence.
234 * @param string $id The service identifier
235 * @param int $invalidBehavior The behavior when the service does not exist
237 * @return object The associated service
239 * @throws ServiceCircularReferenceException When a circular reference is detected
240 * @throws ServiceNotFoundException When the service is not defined
241 * @throws \Exception if an exception has been thrown when the service has been resolved
245 public function get($id, $invalidBehavior = self
::EXCEPTION_ON_INVALID_REFERENCE
)
247 // Attempt to retrieve the service by checking first aliases then
248 // available services. Service IDs are case insensitive, however since
249 // this method can be called thousands of times during a request, avoid
250 // calling strtolower() unless necessary.
252 if (isset($this->aliases
[$id])) {
253 $id = $this->aliases
[$id];
255 // Re-use shared service instance if it exists.
256 if (isset($this->services
[$id]) ||
array_key_exists($id, $this->services
)) {
257 return $this->services
[$id];
259 if ('service_container' === $id) {
263 if (isset($this->loading
[$id])) {
264 throw new ServiceCircularReferenceException($id, array_keys($this->loading
));
267 if (isset($this->methodMap
[$id])) {
268 $method = $this->methodMap
[$id];
269 } elseif (--$i && $id !== $lcId = strtolower($id)) {
272 } elseif (method_exists($this, $method = 'get'.strtr($id, $this->underscoreMap
).'Service')) {
273 // $method is set to the right value, proceed
275 if (self
::EXCEPTION_ON_INVALID_REFERENCE
=== $invalidBehavior) {
277 throw new ServiceNotFoundException($id);
280 $alternatives = array();
281 foreach ($this->getServiceIds() as $knownId) {
282 $lev = levenshtein($id, $knownId);
283 if ($lev <= strlen($id) / 3 ||
false !== strpos($knownId, $id)) {
284 $alternatives[] = $knownId;
288 throw new ServiceNotFoundException($id, null, null, $alternatives);
294 $this->loading
[$id] = true;
297 $service = $this->$method();
298 } catch (\Exception
$e) {
299 unset($this->loading
[$id]);
300 unset($this->services
[$id]);
302 if ($e instanceof InactiveScopeException
&& self
::EXCEPTION_ON_INVALID_REFERENCE
!== $invalidBehavior) {
307 } catch (\Throwable
$e) {
308 unset($this->loading
[$id]);
309 unset($this->services
[$id]);
314 unset($this->loading
[$id]);
321 * Returns true if the given service has actually been initialized.
323 * @param string $id The service identifier
325 * @return bool true if service has already been initialized, false otherwise
327 public function initialized($id)
329 $id = strtolower($id);
331 if (isset($this->aliases
[$id])) {
332 $id = $this->aliases
[$id];
335 if ('service_container' === $id) {
336 // BC: 'service_container' was a synthetic service previously.
337 // @todo Change to false in next major release.
341 return isset($this->services
[$id]) ||
array_key_exists($id, $this->services
);
347 public function reset()
349 if (!empty($this->scopedServices
)) {
350 throw new LogicException('Resetting the container is not allowed when a scope is active.');
353 $this->services
= array();
357 * Gets all service ids.
359 * @return array An array of all defined service ids
361 public function getServiceIds()
364 foreach (get_class_methods($this) as $method) {
365 if (preg_match('/^get(.+)Service$/', $method, $match)) {
366 $ids[] = self
::underscore($match[1]);
369 $ids[] = 'service_container';
371 return array_unique(array_merge($ids, array_keys($this->services
)));
375 * This is called when you enter a scope.
377 * @param string $name
379 * @throws RuntimeException When the parent scope is inactive
380 * @throws InvalidArgumentException When the scope does not exist
382 * @deprecated since version 2.8, to be removed in 3.0.
384 public function enterScope($name)
386 if ('request' !== $name) {
387 @trigger_error
('The '.__METHOD__
.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED
);
390 if (!isset($this->scopes
[$name])) {
391 throw new InvalidArgumentException(sprintf('The scope "%s" does not exist.', $name));
394 if (self
::SCOPE_CONTAINER
!== $this->scopes
[$name] && !isset($this->scopedServices
[$this->scopes
[$name]])) {
395 throw new RuntimeException(sprintf('The parent scope "%s" must be active when entering this scope.', $this->scopes
[$name]));
398 // check if a scope of this name is already active, if so we need to
399 // remove all services of this scope, and those of any of its child
400 // scopes from the global services map
401 if (isset($this->scopedServices
[$name])) {
402 $services = array($this->services
, $name => $this->scopedServices
[$name]);
403 unset($this->scopedServices
[$name]);
405 foreach ($this->scopeChildren
[$name] as $child) {
406 if (isset($this->scopedServices
[$child])) {
407 $services[$child] = $this->scopedServices
[$child];
408 unset($this->scopedServices
[$child]);
413 $this->services
= call_user_func_array('array_diff_key', $services);
414 array_shift($services);
416 // add stack entry for this scope so we can restore the removed services later
417 if (!isset($this->scopeStacks
[$name])) {
418 $this->scopeStacks
[$name] = new \
SplStack();
420 $this->scopeStacks
[$name]->push($services);
423 $this->scopedServices
[$name] = array();
427 * This is called to leave the current scope, and move back to the parent
430 * @param string $name The name of the scope to leave
432 * @throws InvalidArgumentException if the scope is not active
434 * @deprecated since version 2.8, to be removed in 3.0.
436 public function leaveScope($name)
438 if ('request' !== $name) {
439 @trigger_error
('The '.__METHOD__
.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED
);
442 if (!isset($this->scopedServices
[$name])) {
443 throw new InvalidArgumentException(sprintf('The scope "%s" is not active.', $name));
446 // remove all services of this scope, or any of its child scopes from
447 // the global service map
448 $services = array($this->services
, $this->scopedServices
[$name]);
449 unset($this->scopedServices
[$name]);
451 foreach ($this->scopeChildren
[$name] as $child) {
452 if (isset($this->scopedServices
[$child])) {
453 $services[] = $this->scopedServices
[$child];
454 unset($this->scopedServices
[$child]);
459 $this->services
= call_user_func_array('array_diff_key', $services);
461 // check if we need to restore services of a previous scope of this type
462 if (isset($this->scopeStacks
[$name]) && count($this->scopeStacks
[$name]) > 0) {
463 $services = $this->scopeStacks
[$name]->pop();
464 $this->scopedServices +
= $services;
466 if ($this->scopeStacks
[$name]->isEmpty()) {
467 unset($this->scopeStacks
[$name]);
470 foreach ($services as $array) {
471 foreach ($array as $id => $service) {
472 $this->set($id, $service, $name);
479 * Adds a scope to the container.
481 * @throws InvalidArgumentException
483 * @deprecated since version 2.8, to be removed in 3.0.
485 public function addScope(ScopeInterface
$scope)
487 $name = $scope->getName();
488 $parentScope = $scope->getParentName();
490 if ('request' !== $name) {
491 @trigger_error
('The '.__METHOD__
.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED
);
493 if (self
::SCOPE_CONTAINER
=== $name || self
::SCOPE_PROTOTYPE
=== $name) {
494 throw new InvalidArgumentException(sprintf('The scope "%s" is reserved.', $name));
496 if (isset($this->scopes
[$name])) {
497 throw new InvalidArgumentException(sprintf('A scope with name "%s" already exists.', $name));
499 if (self
::SCOPE_CONTAINER
!== $parentScope && !isset($this->scopes
[$parentScope])) {
500 throw new InvalidArgumentException(sprintf('The parent scope "%s" does not exist, or is invalid.', $parentScope));
503 $this->scopes
[$name] = $parentScope;
504 $this->scopeChildren
[$name] = array();
506 // normalize the child relations
507 while (self
::SCOPE_CONTAINER
!== $parentScope) {
508 $this->scopeChildren
[$parentScope][] = $name;
509 $parentScope = $this->scopes
[$parentScope];
514 * Returns whether this container has a certain scope.
516 * @param string $name The name of the scope
520 * @deprecated since version 2.8, to be removed in 3.0.
522 public function hasScope($name)
524 if ('request' !== $name) {
525 @trigger_error
('The '.__METHOD__
.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED
);
528 return isset($this->scopes
[$name]);
532 * Returns whether this scope is currently active.
534 * This does not actually check if the passed scope actually exists.
536 * @param string $name
540 * @deprecated since version 2.8, to be removed in 3.0.
542 public function isScopeActive($name)
544 @trigger_error
('The '.__METHOD__
.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED
);
546 return isset($this->scopedServices
[$name]);
550 * Camelizes a string.
552 * @param string $id A string to camelize
554 * @return string The camelized string
556 public static function camelize($id)
558 return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));
562 * A string to underscore.
564 * @param string $id The string to underscore
566 * @return string The underscored string
568 public static function underscore($id)
570 return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id)));
573 private function __clone()