1. 程式人生 > >PipeStyle PHP鏈式風格

PipeStyle PHP鏈式風格

靈感來自使用linux時的 |xargs ,將巢狀函式改為鏈式風格,意義嘛 來看個例子
$result = abs(round(pow(sin(123),3),1));
》》 0.1
這個是簡單的 ,只有四層括號 ,如果需求改了下 四捨五入從保留1位改為保留2位 - - 是不是在數括號了 如果再增加幾層呢....


相對而言 如果用管道將結果傳遞給下個函式 那虛擬碼是這樣的


123 | sin |  pow 引數 3|round 引數 1|abs


這樣就清爽多了, 用php的魔術方法實現了下這個風格 程式碼如下:




class eItem{
    private $oItem;
    public function __construct($obj){
        $obj and $this->oItem = $obj;
        
        return $this;
    }
    public function __destruct(){
        if ($this->oItem ){ unset($this->oItem); }
    }
    public function __toString(){
        return is_string($this->oItem) ? $this->oItem : (string) $this->oItem;
    }
    public function __get($func){
        $this->oItem and $this->oItem = $func($this->oItem );
        return $this;
    }
        public function __call($func , $args){
        
        if ($this->oItem){
            if (empty($args)){
                $this->oItem = $func($this->oItem);
            }else{
                
                $this->oItem = self::_callFunc($func, $args , $this->oItem);
                
            }
        }
        return $this;
    }
    
    private static function _callFunc($func, $args , $oItem){
        !in_array('$' , $args) and array_unshift($args , '$');
         foreach ($args as &$argv){
                    '$' == $argv and $argv = $oItem;
                }
        $argsCount = is_string($func) ? count($args) : 999;
        switch ($argsCount){
            case 1:
                return  $func($args[0]);
                break;
            case 2:
                return  $func($args[0],$args[1]);
                break; 
            case 3:
                return  $func($args[0],$args[1] , $args[2]);
                break;        
            default:
                return  call_user_func_array($func, $args);
        }
            
    }
    public function call($func , $args = null){
        $this->oItem = self::_callFunc($func, (array)$args , $this->oItem);
        return $this;
    }
    
    public function get(){
        return $this->oItem;
    }
}  




DEMO:


$a = new  eItem(123);
$a = $a->sin->pow('$',3)->round(1)->abs->get() ;
$b = abs(round(pow(sin(123),3),1));
var_dump($a , $b);
>> float(0.1)float(0.1)


ps csdn的blog真難用