PHP code example of yiisoft / proxy

1. Go to this page and download the library: Download yiisoft/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/ */

    

yiisoft / proxy example snippets


use Yiisoft\Proxy\ObjectProxy;

class MyProxy extends ObjectProxy
{
    protected function afterCall(string $methodName, array $arguments, mixed $result, float $timeStart) : mixed {
        $result = parent::afterCall($methodName, $arguments, $result, $timeStart);
        
        $error = $this->getCurrentError(); // Use to track and handle errors. 
        $time = microtime(true) - $timeStart; // Use to measure / log execution time.
        
        return $result;
    }
}

use Yiisoft\Proxy\ProxyManager;

interface CarInterface
{
    public function horsepower(): int;
}

class Car implements CarInterface
{
    public function horsepower(): int
    {
        return 1;
    }
}

$path = sys_get_temp_dir();
$manager = new ProxyManager(
    // This is optional. The proxy can be created "on the fly" instead. But it's recommended to specify path to enable
    // caching.
    $path
);
/** @var Car|MyProxy $object */
$object = $manager->createObjectProxy(
    CarInterface::class,
    MyProxy::class, // Custom base proxy class defined earlier.
    [new Car()]
);
// Now you can call `Car` object methods through proxy the same as you would call it in original `Car` object.
$object->horsepower(); // Outputs "1".

use Yiisoft\Proxy\ProxyManager;

class Car implements CarInterface
{
    public function horsepower(): int
    {
        return 1;
    }
}

$path = sys_get_temp_dir();
$manager = new ProxyManager($path);
/** @var Car|MyProxy $object */
$object = $manager->createObjectProxy(
    Car::class, // Pass class instead of interface here. 
    MyProxy::class, 
    [new Car()]
);

class CarProxy extends MyProxy implements CarInterface
{
    public function horsepower(): int
    {
        return $this->call('horsepower', []);
    }
}