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\EnvNotFoundException;
15 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
16 use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
17 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
18 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
19 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
20 use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
21 use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
24 * Container is a dependency injection container.
26 * It gives access to object instances (services).
27 * Services and parameters are simple key/pair stores.
28 * The container can have four possible behaviors when a service
29 * does not exist (or is not initialized for the last case):
31 * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
32 * * NULL_ON_INVALID_REFERENCE: Returns null
33 * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
34 * (for instance, ignore a setter if the service does not exist)
35 * * IGNORE_ON_UNINITIALIZED_REFERENCE: Ignores/returns null for uninitialized services or invalid references
37 * @author Fabien Potencier <fabien@symfony.com>
38 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
40 class Container implements ResettableContainerInterface
42 protected $parameterBag;
43 protected $services = array();
44 protected $fileMap = array();
45 protected $methodMap = array();
46 protected $aliases = array();
47 protected $loading = array();
48 protected $resolving = array();
49 protected $syntheticIds = array();
54 protected $privates = array();
59 protected $normalizedIds = array();
61 private $underscoreMap = array('_' => '', '.' => '_', '\\' => '_');
62 private $envCache = array();
63 private $compiled = false;
66 public function __construct(ParameterBagInterface $parameterBag = null)
68 $this->parameterBag = $parameterBag ?: new EnvPlaceholderParameterBag();
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());
85 $this->compiled = true;
89 * Returns true if the container is compiled.
93 public function isCompiled()
95 return $this->compiled;
99 * Returns true if the container parameter bag are frozen.
101 * @deprecated since version 3.3, to be removed in 4.0.
103 * @return bool true if the container parameter bag are frozen, false otherwise
105 public function isFrozen()
107 @trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the isCompiled() method instead.', __METHOD__), E_USER_DEPRECATED);
109 return $this->parameterBag instanceof FrozenParameterBag;
113 * Gets the service container parameter bag.
115 * @return ParameterBagInterface A ParameterBagInterface instance
117 public function getParameterBag()
119 return $this->parameterBag;
125 * @param string $name The parameter name
127 * @return mixed The parameter value
129 * @throws InvalidArgumentException if the parameter is not defined
131 public function getParameter($name)
133 return $this->parameterBag->get($name);
137 * Checks if a parameter exists.
139 * @param string $name The parameter name
141 * @return bool The presence of parameter in container
143 public function hasParameter($name)
145 return $this->parameterBag->has($name);
151 * @param string $name The parameter name
152 * @param mixed $value The parameter value
154 public function setParameter($name, $value)
156 $this->parameterBag->set($name, $value);
162 * Setting a service to null resets the service: has() returns false and get()
163 * behaves in the same way as if the service was never created.
165 * @param string $id The service identifier
166 * @param object $service The service instance
168 public function set($id, $service)
170 // Runs the internal initializer; used by the dumped container to include always-needed files
171 if (isset($this->privates['service_container']) && $this->privates['service_container'] instanceof \Closure) {
172 $initialize = $this->privates['service_container'];
173 unset($this->privates['service_container']);
177 $id = $this->normalizeId($id);
179 if ('service_container' === $id) {
180 throw new InvalidArgumentException('You cannot set service "service_container".');
183 if (isset($this->privates[$id]) || !(isset($this->fileMap[$id]) || isset($this->methodMap[$id]))) {
184 if (!isset($this->privates[$id]) && !isset($this->getRemovedIds()[$id])) {
186 } elseif (null === $service) {
187 @trigger_error(sprintf('The "%s" service is private, unsetting it is deprecated since Symfony 3.2 and will fail in 4.0.', $id), E_USER_DEPRECATED);
188 unset($this->privates[$id]);
190 @trigger_error(sprintf('The "%s" service is private, replacing it is deprecated since Symfony 3.2 and will fail in 4.0.', $id), E_USER_DEPRECATED);
192 } elseif (isset($this->services[$id])) {
193 if (null === $service) {
194 @trigger_error(sprintf('The "%s" service is already initialized, unsetting it is deprecated since Symfony 3.3 and will fail in 4.0.', $id), E_USER_DEPRECATED);
196 @trigger_error(sprintf('The "%s" service is already initialized, replacing it is deprecated since Symfony 3.3 and will fail in 4.0.', $id), E_USER_DEPRECATED);
200 if (isset($this->aliases[$id])) {
201 unset($this->aliases[$id]);
204 if (null === $service) {
205 unset($this->services[$id]);
210 $this->services[$id] = $service;
214 * Returns true if the given service is defined.
216 * @param string $id The service identifier
218 * @return bool true if the service is defined, false otherwise
220 public function has($id)
223 if (isset($this->privates[$id])) {
224 @trigger_error(sprintf('The "%s" service is private, checking for its existence is deprecated since Symfony 3.2 and will fail in 4.0.', $id), E_USER_DEPRECATED);
226 if (isset($this->aliases[$id])) {
227 $id = $this->aliases[$id];
229 if (isset($this->services[$id])) {
232 if ('service_container' === $id) {
236 if (isset($this->fileMap[$id]) || isset($this->methodMap[$id])) {
240 if (--$i && $id !== $normalizedId = $this->normalizeId($id)) {
245 // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
246 // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
247 if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, 'get'.strtr($id, $this->underscoreMap).'Service')) {
248 @trigger_error('Generating a dumped container without populating the method map is deprecated since Symfony 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
260 * If a service is defined both through a set() method and
261 * with a get{$id}Service() method, the former has always precedence.
263 * @param string $id The service identifier
264 * @param int $invalidBehavior The behavior when the service does not exist
266 * @return object The associated service
268 * @throws ServiceCircularReferenceException When a circular reference is detected
269 * @throws ServiceNotFoundException When the service is not defined
270 * @throws \Exception if an exception has been thrown when the service has been resolved
274 public function get($id, $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERENCE */ 1)
276 // Attempt to retrieve the service by checking first aliases then
277 // available services. Service IDs are case insensitive, however since
278 // this method can be called thousands of times during a request, avoid
279 // calling $this->normalizeId($id) unless necessary.
281 if (isset($this->privates[$id])) {
282 @trigger_error(sprintf('The "%s" service is private, getting it from the container is deprecated since Symfony 3.2 and will fail in 4.0. You should either make the service public, or stop using the container directly and use dependency injection instead.', $id), E_USER_DEPRECATED);
284 if (isset($this->aliases[$id])) {
285 $id = $this->aliases[$id];
288 // Re-use shared service instance if it exists.
289 if (isset($this->services[$id])) {
290 return $this->services[$id];
292 if ('service_container' === $id) {
296 if (isset($this->loading[$id])) {
297 throw new ServiceCircularReferenceException($id, array_keys($this->loading));
300 $this->loading[$id] = true;
303 if (isset($this->fileMap[$id])) {
304 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->load($this->fileMap[$id]);
305 } elseif (isset($this->methodMap[$id])) {
306 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->{$this->methodMap[$id]}();
307 } elseif (--$i && $id !== $normalizedId = $this->normalizeId($id)) {
308 unset($this->loading[$id]);
311 } elseif (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, $method = 'get'.strtr($id, $this->underscoreMap).'Service')) {
312 // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
313 // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
314 @trigger_error('Generating a dumped container without populating the method map is deprecated since Symfony 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
316 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->{$method}();
320 } catch (\Exception $e) {
321 unset($this->services[$id]);
325 unset($this->loading[$id]);
329 if (/* self::EXCEPTION_ON_INVALID_REFERENCE */ 1 === $invalidBehavior) {
331 throw new ServiceNotFoundException($id);
333 if (isset($this->syntheticIds[$id])) {
334 throw new ServiceNotFoundException($id, null, null, array(), sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id));
336 if (isset($this->getRemovedIds()[$id])) {
337 throw new ServiceNotFoundException($id, null, null, array(), sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.', $id));
340 $alternatives = array();
341 foreach ($this->getServiceIds() as $knownId) {
342 $lev = levenshtein($id, $knownId);
343 if ($lev <= strlen($id) / 3 || false !== strpos($knownId, $id)) {
344 $alternatives[] = $knownId;
348 throw new ServiceNotFoundException($id, null, null, $alternatives);
353 * Returns true if the given service has actually been initialized.
355 * @param string $id The service identifier
357 * @return bool true if service has already been initialized, false otherwise
359 public function initialized($id)
361 $id = $this->normalizeId($id);
363 if (isset($this->privates[$id])) {
364 @trigger_error(sprintf('Checking for the initialization of the "%s" private service is deprecated since Symfony 3.4 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED);
367 if (isset($this->aliases[$id])) {
368 $id = $this->aliases[$id];
371 if ('service_container' === $id) {
375 return isset($this->services[$id]);
381 public function reset()
383 $this->services = array();
387 * Gets all service ids.
389 * @return array An array of all defined service ids
391 public function getServiceIds()
395 if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class) {
396 // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
397 // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
398 @trigger_error('Generating a dumped container without populating the method map is deprecated since Symfony 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
400 foreach (get_class_methods($this) as $method) {
401 if (preg_match('/^get(.+)Service$/', $method, $match)) {
402 $ids[] = self::underscore($match[1]);
406 $ids[] = 'service_container';
408 return array_unique(array_merge($ids, array_keys($this->methodMap), array_keys($this->fileMap), array_keys($this->services)));
412 * Gets service ids that existed at compile time.
416 public function getRemovedIds()
422 * Camelizes a string.
424 * @param string $id A string to camelize
426 * @return string The camelized string
428 public static function camelize($id)
430 return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));
434 * A string to underscore.
436 * @param string $id The string to underscore
438 * @return string The underscored string
440 public static function underscore($id)
442 return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id)));
446 * Creates a service by requiring its factory file.
448 * @return object The service created by the file
450 protected function load($file)
452 return require $file;
456 * Fetches a variable from the environment.
458 * @param string $name The name of the environment variable
460 * @return mixed The value to use for the provided environment variable name
462 * @throws EnvNotFoundException When the environment variable is not found and has no default value
464 protected function getEnv($name)
466 if (isset($this->resolving[$envName = "env($name)"])) {
467 throw new ParameterCircularReferenceException(array_keys($this->resolving));
469 if (isset($this->envCache[$name]) || array_key_exists($name, $this->envCache)) {
470 return $this->envCache[$name];
472 if (!$this->has($id = 'container.env_var_processors_locator')) {
473 $this->set($id, new ServiceLocator(array()));
475 if (!$this->getEnv) {
476 $this->getEnv = new \ReflectionMethod($this, __FUNCTION__);
477 $this->getEnv->setAccessible(true);
478 $this->getEnv = $this->getEnv->getClosure($this);
480 $processors = $this->get($id);
482 if (false !== $i = strpos($name, ':')) {
483 $prefix = substr($name, 0, $i);
484 $localName = substr($name, 1 + $i);
489 $processor = $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
491 $this->resolving[$envName] = true;
493 return $this->envCache[$name] = $processor->getEnv($prefix, $localName, $this->getEnv);
495 unset($this->resolving[$envName]);
500 * Returns the case sensitive id used at registration time.
508 public function normalizeId($id)
510 if (!\is_string($id)) {
513 if (isset($this->normalizedIds[$normalizedId = strtolower($id)])) {
514 $normalizedId = $this->normalizedIds[$normalizedId];
515 if ($id !== $normalizedId) {
516 @trigger_error(sprintf('Service identifiers will be made case sensitive in Symfony 4.0. Using "%s" instead of "%s" is deprecated since Symfony 3.3.', $id, $normalizedId), E_USER_DEPRECATED);
519 $normalizedId = $this->normalizedIds[$normalizedId] = $id;
522 return $normalizedId;
525 private function __clone()