Skip to content

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

Merged
taylorotwell merged 5 commits into
laravel:12.xfrom
daniser:feature/class-attributes-helpers
Apr 29, 2025
Merged

taylorotwell merged 5 commits into
laravel:12.xfrom
daniser:feature/class-attributes-helpers

Conversation

@daniser

@daniser daniser commented Apr 26, 2025 •

Copy link
Copy Markdown
Contributor

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
@taylorotwell
taylorotwell merged commit 186debc into laravel:12.x Apr 29, 2025
@daniser
daniser deleted the feature/class-attributes-helpers branch April 29, 2025 21:08
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.

2 participants