Gets a service.
If a service is defined both through a set() method and with a get{$id}Service() method, the former has always precedence.
@api
string $id The service identifier:
integer $invalidBehavior The behavior when the service does not exist:
object The associated service
InvalidArgumentException if the service is not defined
ServiceCircularReferenceException When a circular reference is detected
ServiceNotFoundException When the service is not defined
Overrides ContainerInterface::get
public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE) {
$id = strtolower($id);
// resolve aliases
if (isset($this->aliases[$id])) {
$id = $this->aliases[$id];
}
// re-use shared service instance if it exists
if (array_key_exists($id, $this->services)) {
return $this->services[$id];
}
if (isset($this->loading[$id])) {
throw new ServiceCircularReferenceException($id, array_keys($this->loading));
}
if (isset($this->methodMap[$id])) {
$method = $this->methodMap[$id];
}
elseif (method_exists($this, $method = 'get' . strtr($id, array(
'_' => '',
'.' => '_',
)) . 'Service')) {
// $method is set to the right value, proceed
}
else {
if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
if (!$id) {
throw new ServiceNotFoundException($id);
}
$alternatives = array();
foreach (array_keys($this->services) as $key) {
$lev = levenshtein($id, $key);
if ($lev <= strlen($id) / 3 || false !== strpos($key, $id)) {
$alternatives[] = $key;
}
}
throw new ServiceNotFoundException($id, null, null, $alternatives);
}
return null;
}
$this->loading[$id] = true;
try {
$service = $this
->{$method}();
} catch (\Exception $e) {
unset($this->loading[$id]);
if (array_key_exists($id, $this->services)) {
unset($this->services[$id]);
}
if ($e instanceof InactiveScopeException && self::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
return null;
}
throw $e;
}
unset($this->loading[$id]);
return $service;
}