Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Created March 11, 2025 22:28
Show Gist options
  • Save diloabininyeri/b84e28915bb51e1f0a1e5bfc3476f177 to your computer and use it in GitHub Desktop.
Save diloabininyeri/b84e28915bb51e1f0a1e5bfc3476f177 to your computer and use it in GitHub Desktop.
example aop wrapper with the autoload
<?php
use Composer\Autoload\ClassLoader;
use Zeus\Trace\Order;
use Zeus\Trace\RealService;
/**
* @var ClassLoader $autoload
*/
$autoload = require 'vendor/autoload.php';
function my_autoload($className)
{
$array = explode('\\', $className);
$class = end($array);
global $autoload;
$file = $autoload->findFile($className);
if (!file_exists($file)) {
return;
}
$code = file_get_contents($file);
$randomName = 'Proxy_mock' . time() . mt_rand();
$realCode = str_replace(
"class $class",
"class $randomName",
$code
);
$code = str_replace(['<?php', '?>'], '', $realCode);
$code = trim($code);
eval($code);
$explode = explode('\\', $className);
array_pop($explode);
$namespace = implode('\\', $explode);
$proxyCode = "
namespace $namespace;
class $class {
private \$service;
public function __construct() {
\$this->service = new \\Zeus\\Trace\\$randomName();
}
public function __call(\$methodName, \$arguments) {
echo \"Before \$methodName\" . PHP_EOL;
echo json_encode(['arguments'=>\$arguments]) . PHP_EOL;
\$result = call_user_func_array([\$this->service, \$methodName], \$arguments);
echo \"After \$methodName\" . PHP_EOL;
echo json_encode(['return'=>\$result]) . PHP_EOL;
return \$result;
}
}
";
try {
eval($proxyCode);
} catch (\ParseError $e) {
echo "Eval failed: " . $e->getMessage() . "\n";
return;
}
}
spl_autoload_register('my_autoload', prepend: true);
// Test
$order = new Order();
$order->setId(5);
$order->getId();
$order->getId();
$order->getId();
$order->getId();
$order->getId();
echo '________________________________________________________________';
echo PHP_EOL;
$order1 = new Order;
$order1->setId(10);
echo '________________________________________________________________';
echo PHP_EOL;
$realService = new RealService();
$realService->hello('John Doe');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment