main
Robert 8 months ago
parent 535c14668d
commit 922e13d022
  1. 9
      src/LazyObject.php
  2. 4
      src/ex/Example2.php
  3. 60
      src/libs/Traits/Macroable.php

@ -13,7 +13,16 @@ $runA = (function(int $i) use ($lazyA) {
});
$lazyB = new libs\LazyObject(ex\Example2::class);
ex\Example2::macro('multiply', function (int $a, int $b) {
echo $this->version;
echo PHP_EOL;
return $a * $b;
});
$objectB = $lazyB->proxy();
$objectB->hi();
echo $objectB->multiply(5, 3);
echo PHP_EOL;
$runA(800);

@ -1,6 +1,10 @@
<?php
namespace ex;
use libs\Traits\Macroable;
class Example2 {
use Macroable;
public int $version = 22;
public function hi(): void { echo "Hi! \n"; }
}

@ -0,0 +1,60 @@
<?php
namespace libs\Traits;
trait Macroable
{
protected static array $macros = [];
/**
* Register a custom macro.
*/
public static function macro(string $name, mixed $macro): void
{
static::$macros[$name] = $macro;
}
/**
* Checks if macro is registered.
*/
public static function hasMacro(string $name): bool
{
return isset(static::$macros[$name]);
}
/**
* Dynamically handle calls to the class.
*/
public function __call(string $method, mixed $parameters): mixed
{
if (!static::hasMacro($method)) {
throw new \BadMethodCallException("Method {$method} does not exist.");
}
$macro = static::$macros[$method];
if ($macro instanceof \Closure) {
return call_user_func_array($macro->bindTo($this, static::class), $parameters);
}
return call_user_func_array($macro, $parameters);
}
/**
* Dynamically handle static calls to the class.
*/
public static function __callStatic(string $method, mixed $parameters): mixed
{
if (!static::hasMacro($method)) {
throw new \BadMethodCallException("Method {$method} does not exist.");
}
$macro = static::$macros[$method];
if ($macro instanceof \Closure) {
return call_user_func_array(\Closure::bind($macro, null, static::class), $parameters);
}
return call_user_func_array($macro, $parameters);
}
}
Loading…
Cancel
Save