How does closing help in creating a DSL / fluent interface: PHP examples?

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

edit: The accepted answer in the next question talks about nested closures. If someone could translate this example into PHP, which would also be useful: Experience with smooth interfaces? I need your opinion!

+4
source share
1 answer

This is the first example I could come up with, it is not very good, 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 will use free interfaces to query my database using some ORM, and then apply some filter to the recordset that I get. Imagine that the run() method returns a RecordSet object that has a filter() method, which could be something like this:

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

Do you have an idea?

+1
source

Source: https://habr.com/ru/post/1310768/


All Articles