Skip to content

Instantly share code, notes, and snippets.

@moolex
Last active December 10, 2015 21:58
Show Gist options
  • Save moolex/4498727 to your computer and use it in GitHub Desktop.
Save moolex/4498727 to your computer and use it in GitHub Desktop.
PHP中类代理机制的简单实现
<?php
/**
* 代理管理
*/
class ProxyManager
{
/**
* 创建类代理
* @param type $className
* @param type $instanceName
*/
public static function create($className, $instanceName = null)
{
is_null($instanceName) && $instanceName = $className;
static $objectPools = array();
if (isset($objectPools[$instanceName]))
{
}
else
{
$objectPools[$instanceName] = new ProxyFramework(new $className());
}
return $objectPools[$instanceName];
}
}
/**
* 代理框架
*/
class ProxyFramework
{
private $object = null;
/**
* 类代理实例
* @param type $object
*/
public function __construct($object)
{
$this->object = $object;
}
/**
* 获取类变量
* @param type $name
*/
public function __get($name)
{
echo '>> Get [' . $name . ']' . "\n";
return $this->object->$name;
}
/**
* 设置类变量
* @param type $name
* @param type $value
*/
public function __set($name, $value)
{
echo '>> Set [' . $name . ']' . "\n";
return $this->object->$name = $value;
}
/**
* 调用类方法
* @param type $name
* @param type $arguments
*/
public function __call($name, $arguments)
{
echo '>> Call [' . $name . ']' . "\n";
return call_user_func_array(array($this->object, $name), $arguments);
}
}
/**
* 测试类
*/
class aClass
{
public function hello()
{
echo 'hello';
}
}
// test
echo '<pre>';
$object = ProxyManager::create('aClass');
$object->string = 'String';
echo $object->string;
echo "\n";
$object->hello();
echo '</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment