nerd-components / nerd-proxy
轻量级对象代理
v0.1
2017-06-09 14:37 UTC
Requires
- php: ^7.0
Requires (Dev)
- phpunit/phpunit: ^6.2
- satooshi/php-coveralls: ^1.0
- squizlabs/php_codesniffer: ^3.0
This package is not auto-updated.
Last update: 2024-09-15 02:27:26 UTC
README
PHP 7 的轻量级对象代理。
用法
创建实现指定接口的对象
<?php use \Nerd\Proxy\Proxy; use \Nerd\Proxy\Handler; interface FooInterface { public function foo(): string; } interface BarInterface { public function bar(): string; } $interfacesList = [FooInterface::class, BarInterface::class]; $handler = new class implements Handler { public function invoke(ReflectionMethod $method, array $args, $proxyInstance) { switch ($method->getName()) { case 'foo': return 'foo called'; case 'bar': return 'bar called'; } } }; $proxy = Proxy::newProxyInstance($handler, $interfacesList); $proxy instanceof FooInterface; // true $proxy instanceof BarInterface; // true $proxy->foo(); // 'foo called' $proxy->bar(); // 'bar called'
为指定对象创建代理
<?php use \Nerd\Proxy\Proxy; use \Nerd\Proxy\Handler; $object = new class { public function foo(): int { echo "Foo! "; return 10; } }; $objectProxy = Proxy::newProxyForObject($object, new class implements Handler { public function invoke(ReflectionMethod $method, array $args, $proxyInstance) { echo "Before call. "; $result = $method->invokeArgs($proxyInstance, $args); echo "After call."; return $result; } }); $objectProxy->foo(); // will print: 'Before call. Foo! After call.' and then return 10