Skip to content

[12.x] Introduce Reflector methods for accessing class attributes #55568

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

Open
wants to merge 4 commits into
base: 12.x
Choose a base branch
from

Conversation

daniser
Copy link
Contributor

@daniser daniser commented Apr 26, 2025

New Reflector methods getClassAttribute and getClassAttributes have been added to simplify/unify access to class attributes.

getClassAttribute method returns instance of desired attribute if found, or null otherwise.

getClassAttributes method is more suited if you want to access repeatable attributes and/or collect attributes up inheritance chain. It returns collection of attribute instances, grouped by class name if ancestor lookup is enabled. This simplifies aggregate operations on child and parent attributes, for example configuration merging:

use Illuminate\Support\Reflector;

#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class ConfigAttr
{
    public function __construct(public array $config) {}
}

#[ConfigAttr(['c' => 3])]
class ParentClass
{
    public static function getConfig(): array
    {
        return Reflector::getClassAttributes(static::class, ConfigAttr::class, true)->flatten()->flatMap->config->all();
    }
}

#[ConfigAttr(['a' => 1]), ConfigAttr(['b' => 2])]
class ChildClass extends ParentClass {}

ChildClass::getConfig();
// ['a' => 1, 'b' => 2, 'c' => 3]

Both methods are properly typehinted.

Update: functions moved into Reflector class.

@daniser daniser changed the title [12.x] Introduce helper functions for accessing class attributes [12.x] Introduce Reflector methods for accessing class attributes Apr 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant