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!
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With