Skip to content

[12.x] Cache Singleton/Scoped attribute checks #56633

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 32 additions & 8 deletions src/Illuminate/Container/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,13 @@ class Container implements ArrayAccess, ContainerContract
*/
protected $checkedForAttributeBindings = [];

/**
* Whether a class has already been checked for Singleton or Scoped attributes.
*
* @var array<class-string, "scoped"|"singleton"|null>
*/
protected $checkedForSingletonOrScopedAttributes = [];

/**
* All of the registered rebound callbacks.
*
Expand Down Expand Up @@ -281,7 +288,7 @@ public function isShared($abstract)
return false;
}

if (($scopedType = $this->getScopedTyped(new ReflectionClass($abstract))) === null) {
if (($scopedType = $this->getScopedTyped($abstract)) === null) {
return false;
}

Expand All @@ -297,20 +304,36 @@ public function isShared($abstract)
/**
* Determine if a ReflectionClass has scoping attributes applied.
*
* @param ReflectionClass<object> $reflection
* @param ReflectionClass<object>|class-string $reflection
* @return "singleton"|"scoped"|null
*/
protected function getScopedTyped(ReflectionClass $reflection): ?string
protected function getScopedTyped(ReflectionClass|string $reflection): ?string
{
if (! empty($reflection->getAttributes(Singleton::class))) {
return 'singleton';
$className = $reflection instanceof ReflectionClass
? $reflection->getName()
: $reflection;

if (array_key_exists($className, $this->checkedForSingletonOrScopedAttributes)) {
return $this->checkedForSingletonOrScopedAttributes[$className];
}

if (! empty($reflection->getAttributes(Scoped::class))) {
return 'scoped';
try {
$reflection = $reflection instanceof ReflectionClass
? $reflection
: new ReflectionClass($reflection);
} catch (ReflectionException) {
return $this->checkedForSingletonOrScopedAttributes[$className] = null;
}

$type = null;

if (! empty($reflection->getAttributes(Singleton::class))) {
$type = 'singleton';
} elseif (! empty($reflection->getAttributes(Scoped::class))) {
$type = 'scoped';
}

return null;
return $this->checkedForSingletonOrScopedAttributes[$className] = $type;
}

/**
Expand Down Expand Up @@ -1753,6 +1776,7 @@ public function flush()
$this->abstractAliases = [];
$this->scopedInstances = [];
$this->checkedForAttributeBindings = [];
$this->checkedForSingletonOrScopedAttributes = [];
}

/**
Expand Down