ryangjchandler / computed-properties
一个小型包,可以为任何PHP类添加计算属性。
v0.2.0
2021-09-03 14:08 UTC
Requires
- php: ^8.0
- spatie/once: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0.0
- pestphp/pest: ^v1.18
- phpstan/phpstan: ^0.12.85
- symfony/var-dumper: ^5.2.7
README
此包提供了一个特质和属性,可以为任何类提供计算属性支持。
安装
可以通过Composer安装此包
composer require ryangjchandler/computed-properties
用法
首先将 RyanChandler\Computed\Traits\WithComputedProperties
特质添加到您的类中
use RyanChandler\Computed\Traits\WithComputedProperties; class Person { use WithComputedProperties; public function getNameProperty() { return 'Ryan'; } }
然后,您可以使用 get[name]Property
命名约定定义一个方法,其中 [name]
是您希望属性名的Pascal大小写版本。
在上面的示例中,我们将能够访问对象上的 name
属性。
$person = new Person; echo $person->name; // 'Ryan'
使用属性
此包还提供了一个 Computed
属性,允许您使用自己的方法名称。
use RyanChandler\Computed\Traits\WithComputedProperties; use RyanChandler\Computed\Attributes\Computed; class Person { use WithComputedProperties; public $firstName = 'Ryan'; public $lastName = 'Chandler'; #[Computed] public function fullName() { return $this->firstName . ' ' . $this->lastName; } }
默认情况下,Computed
允许您使用方法名称访问属性。在上面的示例中,属性将是 fullName
。
$person = new Person; echo $person->fullName; // 'Ryan Chandler'
如果您想更改计算属性的名字,可以向属性传递一个字符串。
use RyanChandler\Computed\Traits\WithComputedProperties; use RyanChandler\Computed\Attributes\Computed; class Person { use WithComputedProperties; public $firstName = 'Ryan'; public $lastName = 'Chandler'; #[Computed("name")] public function fullName() { return $this->firstName . ' ' . $this->lastName; } }
现在,您可以访问 name
属性,它将运行 Person::fullName()
方法。
$person = new Person; echo $person->name; // 'Ryan Chandler'
缓存
如果您希望计算属性在每个请求中只生成一次值,您可以将 RyanChandler\Computed\Attributes\Once
属性添加到您的函数中。
use RyanChandler\Computed\Traits\WithComputedProperties; use RyanChandler\Computed\Attributes\Once; class Person { use WithComputedProperties; #[Once] public function getRandProperty() { return rand(1, 10000); } }
随机数将仅在请求中生成一次。这对于昂贵的计算非常有用。