dongshi8038 2017-12-23 10:45
浏览 34
已采纳

带循环的PHP方法链

Hi I am trying to build a class to emulate Gouette as a learning exercise:

https://github.com/FriendsOfPHP/Goutte/blob/master/README.rst

I think I am on the right track by using method chaining which I think they are doing, what I'm not sure of is how they do something like this:

$crawler->filter('h2 > a')->each(function ($node) {
    print $node->text()."
";
});

Would this be some kind of anonymous function? This is my code so far:

class Bar  
{
    public $b;

    public  function __construct($a=null) {

    }
    public function chain1()
    {
        echo'chain1';
        return $this;
    }

    public function loop($a)
    {
        echo'chain2';       
        return $this;
    }

    public function chain2()
    {
        echo'chain2';       
        return $this;
    }
}

$a=array('bob','andy','sue','rob');
$bar1 = new Bar();
$bar1->chain1()->loop($a)->chain2();
  • 写回答

1条回答 默认 最新

  • dongyue0263 2017-12-23 11:44
    关注

    I've tried to simplify the code to show just this one aspect of what your after...

    class Bar
    {
        private $list;
    
        public  function __construct($a=null) {
            $this->list = $a;
        }
    
        public function each( callable $fn )
        {
            foreach ( $this->list as $value )   {
                $fn($value);
            }
            return $this;
        }
    }
    
    $a=array('bob','andy','sue','rob');
    $bar1 = (new Bar($a))->each(function ($value) {
        print $value."
    ";
    });
    

    As you can see, I've created the object with the list you have, and then just called each() with a callable. You can see the function just takes the passed in value and echoes it out.

    Then in each() there is a loop across all the items in the list provided in the constructor and calls the closure ($fn($value);) with each value from the list.

    The output from this is...

    bob
    andy
    sue
    rob
    

    As for the chained calls, the idea is (as you've worked out) is to return an object which will be the start point for the next call. Some use $this (as you do) some systems (like Request commonly does) return a NEW copy of the object passed in. This is commonly linked to the idea of immutable objects. The idea being that you never change the original object, but you create a new object with the changes made in it. Psr7 Http Message, why immutable? gives some more insight into this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器