decorator
v6.4.3
Python style decorators for PHP
PHP 8.1 or higher
composer require sagittaracc/php-python-decorator
How long it takes to run a method. See the Timer
decorator
use SagittaraccPhpPythondecoratordecorator;
class Calc
{
use decorator;
#[Timer]
function sum($a, $b)
{
sleep(1);
return $a + $b;
}
}
This is how you can call it
$calc = new Calc();
echo call_decorator_func_array([$calc, 'sum'], [1, 2]); // Total execution: 1.00034234 ms; Result: 3
Or inline
$timerOnSum = (new Timer)->wrapper(fn($a, $b) => $calc->sum($a, $b));
echo $timerOnSum(1, 2); // Total execution: 1.00034234 ms; Result: 3
use SagittaraccPhpPythondecoratordecorator;
use SagittaraccPhpPythondecoratormodulesgenericsaliasesT;
use SagittaraccPhpPythondecoratormodulesvalidationcorevalidatorsArrayOf;
#[T]
class Box
{
use decorator;
#[ArrayOf(T::class)]
public $items;
public function addItem(#[T] $item)
{
$this->items[] = $item;
}
}
$box = new Box();
$box(Pen::class); // new Box<Pen>();
call_decorator_func_array([$box, 'addItem'], [new Pencil]); // throws a GenericError
use SagittaraccPhpPythondecoratordecorator;
use SagittaraccPhpPythondecoratortestsexamplesProgress;
use SagittaraccPhpPythondecoratortestsvalidatorsLength;
use SagittaraccPhpPythondecoratortestsvalidatorsSerializeOf;
use SagittaraccPhpPythondecoratortestsvalidatorsIn;
use SagittaraccPhpPythondecoratortestsvalidatorsLessThan;
use SagittaraccPhpPythondecoratortestsvalidatorsUInt8;
class Progress
{
use decorator;
#[UInt8]
public $max;
#[UInt8]
#[LessThan('max')]
public $pos;
#[In('progress', 'finish', 'aborted')]
public $status;
#[Length(32)]
public string $caption;
}
$progress = new Progress();
set_decorator_prop($progress, 'max', 255); // max uint8 - 255
set_decorator_prop($progress, 'pos', 100); // should be less than max
set_decorator_prop($progress, 'status', 'progress'); // status is one of possible cases (progress, finish or aborted)
set_decorator_prop($progress, 'caption', 'in progress ...'); // just a string (max length is 32)
use SagittaraccPhpPythondecoratordecorator;
use SagittaraccPhpPythondecoratormodulesrpccoreRpc;
#[Rpc]
class Controller
{
use decorator;
public function sum($a, $b)
{
return $a + $b;
}
}
in index.php
$requestBody = file_get_contents('php://input');
$controller = new Controller();
$controller($requestBody);
in terminal
$ curl -d "{"id":1,"method":"sum","params":[1,4]}" http://localhost:4000
{"json-rpc":"2.0","id":1,"result":5}
use SagittaraccPhpPythondecoratordecorator;
use SagittaraccPhpPythondecoratormodulesconsolecoreConsole;
class Controller
{
use decorator;
#[Console('hello')]
function greetingPerson($name)
{
return "Hello, $name";
}
}
in the command line it would be calling for example something like this:
php index.php -c hello --name Yuriy
then in index.php
you should read the command and the parameters and after that call it like this:
(new Console('hello'))->setParameters(['name' => 'Yuriy'])->getMethod(Controller::class)->run();