Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active November 27, 2023 11:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/ec06c0165f0a88ad4b0448203e15a535 to your computer and use it in GitHub Desktop.
Save ziadoz/ec06c0165f0a88ad4b0448203e15a535 to your computer and use it in GitHub Desktop.
Using PHP 8.0 Attributes/Annotations To Decorate Functions
<?php
// Attributes (AKA Annotations).
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_FUNCTION)]
class CharDecoratorAttribute
{
public function __construct(protected string $char) // Constructor Property Promotion
{
}
public function decorate(Closure $fn): Closure
{
return fn(string $str): string => $this->char . $fn($str) . $this->char;
}
}
// Function decorated using Attributes with Named Parameters.
$xmas =
#[CharDecoratorAttribute(char: '🎄')]
#[CharDecoratorAttribute(char: '⛄️')]
#[CharDecoratorAttribute(char: '🎅')]
fn (string $str): string => $str;
// Use Reflection to get and instantiate Attributes, and then decorate the function.
function decorateFn(Closure $fn) {
return array_reduce(
array: (new ReflectionFunction($fn))->getAttributes(CharDecoratorAttribute::class),
callback: fn($fn, $attribute) => $attribute->newInstance()->decorate($fn),
initial: $fn,
);
}
echo decorateFn($xmas)(str: 'Merry Christmas'); // 🎅⛄️🎄Merry Christmas🎄⛄️🎅
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment