[英]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 .
作为参考,我指的是由traits组成的特征 。
Scenario: I have classes for models User
, Account
and Lead
. 场景:我有模型类
User
, Account
和Lead
。 I have traits called People
, Importable
, Exportable
, Validatable
, ImplicitAttributable
, Auditable
, Listable
, Permitable
, Searchable
, Encryptable
, Hashable
, Currentable
, Relatable
and Triggerable
. 我有特质叫
People
, Importable
, Exportable
, Validatable
, ImplicitAttributable
, Auditable
, Listable
, Permitable
, Searchable
, Encryptable
, Hashable
, Currentable
, Relatable
和Triggerable
。 All 3 classes implement the People
trait. 这三个类别均实现了
People
特质。
The trait called People
is composed of Auditable
, Listable
, Permitable
, Searchable
, Encryptable
, Hashable
, Currentable
, Relatable
and Triggerable
. 这种特点被称为
People
组成的Auditable
, Listable
, Permitable
, Searchable
, Encryptable
, Hashable
, Currentable
, Relatable
和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. 但是,当我尝试用特征
Searchable
过滤该特征时,该特征在模型之一中没有明确定义(而是它是组合特征People
的一部分),但没有任何结果。
Current Methods Used: 当前使用的方法:
I've tried to use PHP's class_uses and the following function: 我尝试使用PHP的class_uses和以下功能:
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. 我在列表中获得了
People
特质,但没有得到Searchable
特质。
Additional Information: 附加信息:
I'm building my application using Laravel 5.7 with PHP 7.1.23. 我正在使用Laravel 5.7和PHP 7.1.23构建应用程序。
It turns out that ReflectionClass
can also be used on Traits. 事实证明,
ReflectionClass
也可以在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. 而且我能够获得性状的完整列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.