PipeStyle PHP管道风格

灵感来自使用linux时的 |xargs ,将嵌套函数改为链式风格,意义嘛 来看个例子
$result = abs(round(pow(sin(123),3),1));
》》 0.1
这个是简单的 ,只有四层括号 ,如果需求改了下 四舍五入从保留1位改为保留2位 - - 是不是在数括号了 如果再增加几层呢....

相对而言 如果用管道将结果传递给下个函数 那伪代码是这样的

123 | sin |  pow 参数 3|round 参数 1|abs

这样就清爽多了, 用php的魔术方法实现了下这个风格 代码如下:

 

 1 class eItem{
2 private $oItem;
3 public function __construct($obj){
4 $obj and $this->oItem = $obj;
5
6 return $this;
7 }
8 public function __destruct(){
9 if ($this->oItem ){ unset($this->oItem); }
10 }
11 public function __toString(){
12 return is_string($this->oItem) ? $this->oItem : (string) $this->oItem;
13 }
14 public function __get($func){
15 $this->oItem and $this->oItem = $func($this->oItem );
16 return $this;
17 }
18 public function __call($func , $args){
19
20 if ($this->oItem){
21 if (empty($args)){
22 $this->oItem = $func($this->oItem);
23 }else{
24
25 $this->oItem = self::_callFunc($func, $args , $this->oItem);
26
27 }
28 }
29 return $this;
30 }
31
32 private static function _callFunc($func, $args , $oItem){
33 !in_array('$' , $args) and array_unshift($args , '$');
34 foreach ($args as &$argv){
35 '$' == $argv and $argv = $oItem;
36 }
37 $argsCount = is_string($func) ? count($args) : 999;
38 switch ($argsCount){
39 case 1:
40 return $func($args[0]);
41 break;
42 case 2:
43 return $func($args[0],$args[1]);
44 break;
45 case 3:
46 return $func($args[0],$args[1] , $args[2]);
47 break;
48 default:
49 return call_user_func_array($func, $args);
50 }
51
52 }
53 public function call($func , $args = null){
54 $this->oItem = self::_callFunc($func, (array)$args , $this->oItem);
55 return $this;
56 }
57 public function get(){
58 return $this->oItem;
59 }
60 }

 

1 $a = new  eItem(123);
2 $a = $a->sin->pow(3)->round(1)->abs ;
3 $b = abs(round(pow(sin(123),3),1));
4 echo "a : $a " ;
5 echo "b : $b " ;

a : 0.1
b : 0.1


posted on 2011-12-02 15:13  雨弓  阅读(315)  评论(0编辑  收藏  举报