yceruto/decorator

PHP 函数装饰器

v1.0.0 2024-09-19 05:10 UTC

This package is auto-updated.

Last update: 2024-09-19 05:12:30 UTC


README

GitHub Actions Workflow Status Version PHP GitHub License

注意

灵感来自 Python 的装饰器

此库实现了 装饰器模式,围绕任何 PHP 可调用对象,允许您

  • 在可调用对象执行前后执行逻辑
  • 通过提前返回来跳过可调用对象的执行
  • 修改可调用对象的结果

安装

composer require yceruto/decorator

用法

use Yceruto\Decorator\Attribute\DecoratorAttribute;
use Yceruto\Decorator\CallableDecorator;
use Yceruto\Decorator\DecoratorInterface;

#[\Attribute(\Attribute::TARGET_METHOD)]
class Debug extends DecoratorAttribute
{
}

class DebugDecorator implements DecoratorInterface
{
    public function decorate(\Closure $func): \Closure
    {
        return function (mixed ...$args) use ($func): mixed
        {
            echo "Do something before\n";

            $result = $func(...$args);

            echo "Do something after\n";

            return $result;
        };
    }
}

class Greeting
{
    #[Debug]
    public function sayHello(string $name): void
    {
        echo "Hello $name!\n";
    }
}

$greeting = new Greeting();
$decorator = new CallableDecorator();
$decorator->call($greeting->sayHello(...), 'John');

输出

Do something before
Hello John!
Do something after

许可证

此软件在 MIT 许可证 下发布