Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do closures help in creating a DSL/fluent interface: PHP examples?

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!

like image 212
koen Avatar asked Nov 06 '22 12:11

koen


1 Answers

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?

like image 167
El Barto Avatar answered Nov 12 '22 14:11

El Barto