Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Static Proxy trait
<?php
/**
* Simple static proxy trait
*
* Aura DI is used for lazy loading
*
* Set `const PROXY_IDENTIFIER = "SomeClass" in your proxy class, and use this trait.
*
* Call `Some\Proxy\SomeClass::register(new SomeClassInstance)` to have it register the alias.
*
* @license MIT
* @author David Lundgren <github.com/dlundgren>
* @copyright 2017 David Lundgren
*/
trait IsStaticProxy
{
/**
* The instance of the proxy object
*
* @var object
*/
private static $proxyInstance;
/**
* Protect the constructor
*/
protected function __construct()
{}
/**
* Registers the proxy instance
*
* This will add a class alias for the classes PROXY_IDENTIFIER and the instance itself
*
* @param $instance
*/
public static function register($instance)
{
class_alias(__CLASS__, static::PROXY_IDENTIFIER);
self::$proxyInstance = $instance;
}
/**
* Calls the methods on the instance
*
* @magic
* @param string $name
* @param array $arguments
* @return mixed
*/
public static function __callStatic($name, $arguments)
{
return call_user_func_array([self::proxyInstance(), $name], $arguments);
}
/**
* Returns the proxy instance
*
* If it's an instance of a Aura DI's LazyInterface then initialize it first
*
* @return object
*/
private static function proxyInstance()
{
if (self::$proxyInstance instanceof \Aura\Di\Injection\LazyInterface) {
self::$proxyInstance = (self::$proxyInstance)();
}
return self::$proxyInstance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment