authanram / attributes
Low level utilization of PHP8 attributes
Installs: 12
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Type:package
Requires
- php: ^8.0
Requires (Dev)
- nunomaduro/phpinsights: ^2.0.1
- pestphp/pest: ^1.20.0
- pestphp/pest-plugin-mock: ^1.0.3
This package is auto-updated.
Last update: 2024-10-24 02:09:52 UTC
README
Simple usage of attributes brought by PHP8.
Install
composer require authanram/attributes
Usage
Create an attribute class for any purpose, casting, mapping, etc.
<?php namespace AwesomeProject\Attributes; #[Attribute(Attribute::TARGET_PROPERTY)] AwesomeAttribute { /** * @param mixed ...$args // ['whatever', 'data'] */ public funtion __construct(mixed ...$args) {} /** * @param object $context // Instance of AwesomeProject\AwesomeClass * @param string $name // 'foo' (The name of the property the attribute belongs to) * @param mixed ...$args // ['your', 'args'] * * @return void */ public function handle(object $context, string $name, mixed ...$args) { } /** * @param mixed $old // 'qux' * * @return string */ public function value(mixed $old): string { return 'bar'; } }
Use your Attribute (somewhere)
For e.g.
<?php namespace AwesomeProject; use Authanram\Attributes; AwesomeClass { #[Attributes\AwesomeAttribute('whatever', 'data')] public string $foo = 'qux'; public function __construct() { new Attributes($this, 'your', 'args'); } }
Create an Instance
$instance = new \AwesomeProject\AwesomeClass(); $instance->foo; // 'bar'
Some Words
The methods handle
and value
will only be called if present. Means if the constructor (and
arguments) plus of one these methods will fit to your needs, the other one can be omitted.
Under the hood an instance of the attribute class will be created and the methods handle
and
value
will be called, if present.
The return value of the method value
will be assigned the corresponding property. Through the
arguments $context
and $name
, passed to the method handle
, you'll be able to assign a value
manually to the property the attribute belongs to, e.g. $context->{$name} = 'qux';
In general, this should equip you with some low level tools to utilize attributes in your code.
Testing
vendor/bin/pest