PipeStyle PHP管道风格

本文介绍了一种在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


转载于:https://www.cnblogs.com/vaal-water/articles/php-pipeStyle.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值