PHP code example of nerd-components / nerd-proxy

1. Go to this page and download the library: Download nerd-components/nerd-proxy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nerd-components / nerd-proxy example snippets




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'



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