Created
February 27, 2017 08:30
-
-
Save dlundgren/34a9dab1eac8841d80a21b2528369dfd to your computer and use it in GitHub Desktop.
Static Proxy trait
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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