5

Can you give me an example, in PHP, that shows how closures are helpful in creating a DSL (fluent interface)?

edit: The accepted answer in the following question tells about nested closures. If someone could translate that example to PHP that would be helpful too: Experience with fluent interfaces? I need your opinion!

Community
  • 1
  • 1
koen
  • 13,349
  • 10
  • 46
  • 51

1 Answers1

2

This is the first example I could think of, it's not great but it gives you an idea:

$db = new Database();
$filteredList = $db->select()
           ->from('my_table')
           ->where('id', 9)
           ->run()
           ->filter(function($record){
            // apply some php code to filter records
        });

There I'd be using fluent interfaces to query my database using some ORM and then applying some filter to the recordset I get. Imagine the run() method returns a RecordSet object which has a filter() method that could be something like this:

public function filter ($callback)
{
    return array_filter($this->recordSet, $callback);
}

Do you get the idea?

El Barto
  • 919
  • 1
  • 5
  • 18
  • Could you maybe also give a specific example for nested closure with objects? In the link provided by the original poster the accepted answer gives the following example to prevent dead-ending: `Database .ConnectionString(cs => cs.User("name"); .Pass("xxx")) .Timeout(100);` How would you do this in PHP? As far as I tried, you cannot mimic this construct in PHP – qrazi Dec 12 '12 at 14:15
  • I'm not sure if I understand the problem or how is it being solved in Java. However, I'm sure there's some way around it in PHP (although it may differ from how it's done in Java). – El Barto Dec 12 '12 at 17:45
  • It's actually C#. I'm working on functional testing with Selenium and PHPUnit, using Page Object pattern. I'd like to use the page objects in a fluent way. So lets say I have a pageA object and a pageB object, both of which use the same kind of popup (pageC). When closing the popup, which object to you return? In the C# example you don't have to worry about that, because of the nested closure. In my example that would mean that when closing the popup, you exit the closure and continue with either pageA or pageB. – qrazi Dec 13 '12 at 10:21
  • I tried using an anonymous function, but struggled with $this among other things inside the anonymous function. The alternative would be to keep track of the parent (binary tree maybe?) and use that to traverse back to the needed object. For now I just stop the chaining, and put the popup in a new variable, do my things and then go back to the first variable. – qrazi Dec 13 '12 at 10:24
  • Hehe you're right, it's C#, I don't know what I was looking at. I suggest that you ask a new question, pasting some sample code so that me and also other people can see it and help you out. – El Barto Dec 13 '12 at 14:27