-
-
Save matancohen365/942105c518ebf4ab739ef69cdf5b1424 to your computer and use it in GitHub Desktop.
A simple example of using a Lazy Loading Proxy object in PHP. It is useful when attempting to work with legacy code for logging and memory savings when working with global objects..
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 | |
| require __DIR__.'/vendor/autoload.php'; | |
| /** @var Client $client */ | |
| $client = new LazyLoadingProxy(\GuzzleHttp\Client::class); | |
| echo $client->get('http://google.com')->getStatusCode(); // 200 |
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 | |
| class LazyLoadingProxy { | |
| /** | |
| * @var string | |
| */ | |
| protected $class; | |
| /** | |
| * @var object | |
| */ | |
| protected $instance; | |
| /** | |
| * @var array | |
| */ | |
| protected $args; | |
| /** | |
| * Proxy constructor. | |
| * @param string $class | |
| * @param array ...$args | |
| */ | |
| public function __construct($class, ...$args) | |
| { | |
| $this->class = $class; | |
| $this->args = $args; | |
| } | |
| /** | |
| * @return object | |
| */ | |
| protected function getInstance() | |
| { | |
| if(is_null($this->instance)) { | |
| $this->instance = new $this->class(...$this->args); | |
| } | |
| return $this->instance; | |
| } | |
| /** | |
| * @param string $name | |
| * @param array $args | |
| * @return mixed | |
| */ | |
| public function __call($name, $args) | |
| { | |
| return call_user_func_array([$this->getInstance(), $name], $args); | |
| } | |
| /** | |
| * @param string $name | |
| * @return mixed | |
| */ | |
| public function __get($name) | |
| { | |
| return $this->getInstance()->{$name}; | |
| } | |
| /** | |
| * @param string $name | |
| * @param mixed $value | |
| */ | |
| public function __set($name, $value) | |
| { | |
| $this->getInstance()->{$name} = $value; | |
| } | |
| /** | |
| * @param string $name | |
| * @return bool | |
| */ | |
| public function __isset($name) | |
| { | |
| return isset($this->getInstance()->{$name}); | |
| } | |
| /** | |
| * @param string $name | |
| */ | |
| public function __unset($name) | |
| { | |
| unset($this->getInstance()->{$name}); | |
| } | |
| public function __clone() | |
| { | |
| $this->instance = clone $this->instance; | |
| } | |
| /** | |
| * @return string | |
| */ | |
| public function __toString() | |
| { | |
| return $this->getInstance()->__toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment