0

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()."\n";
});

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();
craig_h
  • 31,871
  • 6
  • 59
  • 68
Ian
  • 900
  • 2
  • 9
  • 19

1 Answers1

1

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."\n";
});

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.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55