| 1 | <?php |
|---|
| 2 | |
|---|
| 3 | |
|---|
| 4 | |
|---|
| 5 | |
|---|
| 6 | class Hermit { |
|---|
| 7 | protected $proxy; |
|---|
| 8 | protected $calls = array(); |
|---|
| 9 | protected static $behaviors = array(); |
|---|
| 10 | public function __construct($class = null){ |
|---|
| 11 | if(is_null($class)){ |
|---|
| 12 | $e = new Exception; |
|---|
| 13 | $trace = $e->getTrace(); |
|---|
| 14 | $class = HermitDaoManager::get($trace[1]['class']); |
|---|
| 15 | } else if(HermitDaoManager::has($class)){ |
|---|
| 16 | $class = HermitDaoManager::get($class); |
|---|
| 17 | } |
|---|
| 18 | $this->proxy = self::__create($class); |
|---|
| 19 | } |
|---|
| 20 | public function __call($name, $parameters = array()){ |
|---|
| 21 | if(0 < count($this->calls)){ |
|---|
| 22 | foreach($this->calls as $call){ |
|---|
| 23 | if($call->has($name)){ |
|---|
| 24 | return $call->execute($this->proxy, $name, $parameters); |
|---|
| 25 | } |
|---|
| 26 | } |
|---|
| 27 | } |
|---|
| 28 | return self::__request($this->proxy, $name, $parameters); |
|---|
| 29 | } |
|---|
| 30 | protected static function __request(HermitProxy $proxy, $name, array $params){ |
|---|
| 31 | return $proxy->request($name, $params); |
|---|
| 32 | } |
|---|
| 33 | protected static function __create($targetClass){ |
|---|
| 34 | $proxy = null; |
|---|
| 35 | $reflector = null; |
|---|
| 36 | $ctx = null; |
|---|
| 37 | if(is_object($targetClass)){ |
|---|
| 38 | $reflector = new ReflectionObject($targetClass); |
|---|
| 39 | $ctx = new HermitContext($reflector); |
|---|
| 40 | $proxy = HermitObjectProxy::delegate($ctx, $reflector, $targetClass); |
|---|
| 41 | } else { |
|---|
| 42 | $reflector = new ReflectionClass($targetClass); |
|---|
| 43 | $ctx = new HermitContext($reflector); |
|---|
| 44 | if($reflector->isInterface()){ |
|---|
| 45 | $proxy = HermitInterfaceProxy::delegate($ctx, $reflector); |
|---|
| 46 | } else { |
|---|
| 47 | $proxy = HermitClassProxy::delegate($ctx, $reflector); |
|---|
| 48 | } |
|---|
| 49 | } |
|---|
| 50 | return self::wrap($ctx, $proxy); |
|---|
| 51 | } |
|---|
| 52 | protected static function wrap(HermitContext $ctx, HermitProxy $proxy){ |
|---|
| 53 | if(0 < count(self::$behaviors)){ |
|---|
| 54 | $targetClass = $ctx->getName(); |
|---|
| 55 | foreach(self::$behaviors as $behavior){ |
|---|
| 56 | if($behavior->has($targetClass)){ |
|---|
| 57 | return $behavior->createProxy($ctx, $proxy); |
|---|
| 58 | } |
|---|
| 59 | } |
|---|
| 60 | } |
|---|
| 61 | return $proxy; |
|---|
| 62 | } |
|---|
| 63 | } |
|---|