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\ServiceNotFoundException;
17 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
18 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
19 use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
20 use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
23 * Container is a dependency injection container.
25 * It gives access to object instances (services).
27 * Services and parameters are simple key/pair stores.
29 * Parameter and service keys are case insensitive.
31 * A service can also be defined by creating a method named
32 * getXXXService(), where XXX is the camelized version of the id:
35 * <li>request -> getRequestService()</li>
36 * <li>mysql_session_storage -> getMysqlSessionStorageService()</li>
37 * <li>symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()</li>
40 * The container can have three possible behaviors when a service does not exist:
42 * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
43 * * NULL_ON_INVALID_REFERENCE: Returns null
44 * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
45 * (for instance, ignore a setter if the service does not exist)
47 * @author Fabien Potencier <fabien@symfony.com>
48 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
50 class Container implements ResettableContainerInterface
53 * @var ParameterBagInterface
55 protected $parameterBag;
57 protected $services = array();
58 protected $methodMap = array();
59 protected $aliases = array();
60 protected $loading = array();
65 protected $privates = array();
67 private $underscoreMap = array('_' => '', '.' => '_', '\\' => '_');
68 private $envCache = array();
71 * @param ParameterBagInterface $parameterBag A ParameterBagInterface instance
73 public function __construct(ParameterBagInterface $parameterBag = null)
75 $this->parameterBag = $parameterBag ?: new EnvPlaceholderParameterBag();
79 * Compiles the container.
81 * This method does two things:
83 * * Parameter values are resolved;
84 * * The parameter bag is frozen.
86 public function compile()
88 $this->parameterBag->resolve();
90 $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
94 * Returns true if the container parameter bag are frozen.
96 * @return bool true if the container parameter bag are frozen, false otherwise
98 public function isFrozen()
100 return $this->parameterBag instanceof FrozenParameterBag;
104 * Gets the service container parameter bag.
106 * @return ParameterBagInterface A ParameterBagInterface instance
108 public function getParameterBag()
110 return $this->parameterBag;
116 * @param string $name The parameter name
118 * @return mixed The parameter value
120 * @throws InvalidArgumentException if the parameter is not defined
122 public function getParameter($name)
124 return $this->parameterBag->get($name);
128 * Checks if a parameter exists.
130 * @param string $name The parameter name
132 * @return bool The presence of parameter in container
134 public function hasParameter($name)
136 return $this->parameterBag->has($name);
142 * @param string $name The parameter name
143 * @param mixed $value The parameter value
145 public function setParameter($name, $value)
147 $this->parameterBag->set($name, $value);
153 * Setting a service to null resets the service: has() returns false and get()
154 * behaves in the same way as if the service was never created.
156 * @param string $id The service identifier
157 * @param object $service The service instance
159 public function set($id, $service)
161 $id = strtolower($id);
163 if ('service_container' === $id) {
164 throw new InvalidArgumentException('You cannot set service "service_container".');
167 if (isset($this->aliases[$id])) {
168 unset($this->aliases[$id]);
171 $this->services[$id] = $service;
173 if (null === $service) {
174 unset($this->services[$id]);
177 if (isset($this->privates[$id])) {
178 if (null === $service) {
179 @trigger_error(sprintf('Unsetting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED);
180 unset($this->privates[$id]);
182 @trigger_error(sprintf('Setting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0. A new public service will be created instead.', $id), E_USER_DEPRECATED);
188 * Returns true if the given service is defined.
190 * @param string $id The service identifier
192 * @return bool true if the service is defined, false otherwise
194 public function has($id)
197 if (isset($this->privates[$id])) {
198 @trigger_error(sprintf('Checking for the existence of the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED);
201 if ('service_container' === $id
202 || isset($this->aliases[$id])
203 || isset($this->services[$id])
208 if (isset($this->methodMap[$id])) {
212 if (--$i && $id !== $lcId = strtolower($id)) {
217 // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
218 // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
219 if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, 'get'.strtr($id, $this->underscoreMap).'Service')) {
220 @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
232 * If a service is defined both through a set() method and
233 * with a get{$id}Service() method, the former has always precedence.
235 * @param string $id The service identifier
236 * @param int $invalidBehavior The behavior when the service does not exist
238 * @return object The associated service
240 * @throws ServiceCircularReferenceException When a circular reference is detected
241 * @throws ServiceNotFoundException When the service is not defined
242 * @throws \Exception if an exception has been thrown when the service has been resolved
246 public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
248 // Attempt to retrieve the service by checking first aliases then
249 // available services. Service IDs are case insensitive, however since
250 // this method can be called thousands of times during a request, avoid
251 // calling strtolower() unless necessary.
253 if (isset($this->privates[$id])) {
254 @trigger_error(sprintf('Requesting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED);
256 if (isset($this->aliases[$id])) {
257 $id = $this->aliases[$id];
260 // Re-use shared service instance if it exists.
261 if (isset($this->services[$id])) {
262 return $this->services[$id];
264 if ('service_container' === $id) {
268 if (isset($this->loading[$id])) {
269 throw new ServiceCircularReferenceException($id, array_keys($this->loading));
272 if (isset($this->methodMap[$id])) {
273 $method = $this->methodMap[$id];
274 } elseif (--$i && $id !== $lcId = strtolower($id)) {
277 } elseif (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, $method = 'get'.strtr($id, $this->underscoreMap).'Service')) {
278 // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
279 // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
280 @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
281 // $method is set to the right value, proceed
283 if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
285 throw new ServiceNotFoundException($id);
288 $alternatives = array();
289 foreach ($this->getServiceIds() as $knownId) {
290 $lev = levenshtein($id, $knownId);
291 if ($lev <= strlen($id) / 3 || false !== strpos($knownId, $id)) {
292 $alternatives[] = $knownId;
296 throw new ServiceNotFoundException($id, null, null, $alternatives);
302 $this->loading[$id] = true;
305 $service = $this->$method();
306 } catch (\Exception $e) {
307 unset($this->services[$id]);
311 unset($this->loading[$id]);
319 * Returns true if the given service has actually been initialized.
321 * @param string $id The service identifier
323 * @return bool true if service has already been initialized, false otherwise
325 public function initialized($id)
327 $id = strtolower($id);
329 if (isset($this->aliases[$id])) {
330 $id = $this->aliases[$id];
333 if ('service_container' === $id) {
337 return isset($this->services[$id]);
343 public function reset()
345 $this->services = array();
349 * Gets all service ids.
351 * @return array An array of all defined service ids
353 public function getServiceIds()
357 if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class) {
358 // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
359 // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
360 @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
362 foreach (get_class_methods($this) as $method) {
363 if (preg_match('/^get(.+)Service$/', $method, $match)) {
364 $ids[] = self::underscore($match[1]);
368 $ids[] = 'service_container';
370 return array_unique(array_merge($ids, array_keys($this->methodMap), array_keys($this->services)));
374 * Camelizes a string.
376 * @param string $id A string to camelize
378 * @return string The camelized string
380 public static function camelize($id)
382 return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));
386 * A string to underscore.
388 * @param string $id The string to underscore
390 * @return string The underscored string
392 public static function underscore($id)
394 return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id)));
398 * Fetches a variable from the environment.
400 * @param string The name of the environment variable
402 * @return scalar The value to use for the provided environment variable name
404 * @throws EnvNotFoundException When the environment variable is not found and has no default value
406 protected function getEnv($name)
408 if (isset($this->envCache[$name]) || array_key_exists($name, $this->envCache)) {
409 return $this->envCache[$name];
411 if (isset($_ENV[$name])) {
412 return $this->envCache[$name] = $_ENV[$name];
414 if (false !== $env = getenv($name)) {
415 return $this->envCache[$name] = $env;
417 if (!$this->hasParameter("env($name)")) {
418 throw new EnvNotFoundException($name);
421 return $this->envCache[$name] = $this->getParameter("env($name)");
424 private function __clone()