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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号