The product is learned from Martin's "Enterprise Application Architecture Model", and the features of the helper PHP Dynamic language can be deferred more easily than Java implementations-through a virtual proxy placeholder. The only drawback is that you can only proxy objects and cannot proxy built-in base types.
I test the water in the PHP domain model design, it is also used to implement DomainObject delay loading.
Copy Code code as follows:
* Virtual proxy, which calls the closure function to generate the target object only when the member is accessed.
*
* @author Tonyseek
*
*/
Class Virtualproxy
{
Private $holder = null;
Private $loader = null;
/**
* Virtual proxy, which calls the closure function to generate the target object only when the member is accessed.
*
* @param Closure $loader to generate closure functions for the proxy object
*/
Public function __construct (Closure $loader)
{
$this->loader = $loader;
}
/**
* Invocation of Proxy member method
*
* @param string $method
* @param array $arguments
* @throws badmethodcallexception
* @return Mixed
*/
Public Function __call ($method, array $arguments = null)
{
$this->check ();
if (!method_exists ($this->holder, $method)) {
throw new Badmethodcallexception ();
}
Return Call_user_func_array (
Array (& $this->holder, $method),
$arguments);
}
/**
* Agent member properties read
*
* @param string $property
* @throws errorexception
* @return Mixed
*/
Public Function __get ($property)
{
$this->check ();
if (!isset ($this->holder-> $property)) {
throw new Errorexception ();
}
return $this->holder-> $property;
}
/**
* Assignment of Proxy member properties
*
* @param string $property
* @param mixed $value
*/
Public Function __set ($property, $value)
{
$this->check ();
$this->holder-> $property = $value;
}
/**
* Checks whether the proxy object already exists and is generated if it does not exist.
*/
private Function check ()
{
& nbsp; if (null = = $this->holder) {
$loader = $this- >loader;
$this->holder = $loader ();
}
}
}
Test
$v = new Virtualproxy (function () {
Echo ' Now, Loading ', "\ n";
$a = new Arrayobject (range (1,100));
$a->abc = ' a ';
In actual use, this is called the Datamapper findxxx method.
Returns a collection of Realm objects
return $a;
});
Proxy object is accessed directly as the original object
The callback function passed in by the constructor is then invoked
Thus implementing the delay in loading object operations
Echo $v->abc. $v->offsetget (50);