简体   繁体   中英

How to get list of traits which a trait is composed of

Question: Is there a way to get a list of the traits which a trait is composed of? For reference, I'm refering to traits composed from traits .

Scenario: I have classes for models User , Account and Lead . I have traits called People , Importable , Exportable , Validatable , ImplicitAttributable , Auditable , Listable , Permitable , Searchable , Encryptable , Hashable , Currentable , Relatable and Triggerable . All 3 classes implement the People trait.

The trait called People is composed of Auditable , Listable , Permitable , Searchable , Encryptable , Hashable , Currentable , Relatable and Triggerable .

I am trying to filter my classes by traits. However, when I try to filter the by the trait Searchable , which isn't specifically defined on one of the models (instead it's part of the composed trait People ), I get no results.

Current Methods Used:

I've tried to use PHP's class_uses and the following function:

function getTraitsForClass($class)
{
    return array_keys((new \ReflectionClass($class))->getTraits());
}

to generate the list of traits to filter by. I get the People trait in the list, but I don't get the Searchable trait.

Additional Information:

I'm building my application using Laravel 5.7 with PHP 7.1.23.

It turns out that ReflectionClass can also be used on Traits. So I modified my function to:

function getTraitsForClass($something)
{
    $traits = array_keys((new \ReflectionClass($something))->getTraits());
    foreach ($traits as $trait) {
        $traits = array_merge($traits, getTraitsForClass($trait));
    }
    $traits = array_unique($traits);
    return $traits;
}

And I was able to get the full list of traits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM