In PHP, I want to see examples of useful/powerful internal DSL like code, tricks, or hacks. I will subsequently refer to these as DSLs.
A good answer will start with an inspiring code example of how the DSL can be used. This will help us to understand why we should even care about this DSL. An even better answer would also contain some or all of the DSL implementation, or where we can access it. An even better answer would also contain explanations of when this can be a good idea and when it can get you into trouble.
In case you are having trouble thinking of how you could create a DSL in PHP, here are some language features of PHP that can be used/exploited for creating internal DSLs:
- the general looseness of PHP
- magic methods
- dynamically adding properties to objects:
class o { } $obj = new o; $obj->name = 'Bob'; - anonymous functions (closures)
- functions automatically return null if nothing specifically returned.
- IteratorAggregate and Iterator can be used to make classes support foreach.
- reflection
- variables and even object properties can be referred to inside strings without escaping the string:
"Hello, my name is $obj->name!" eval($code);(I know its use is discouraged and can get you into a lot of trouble, but I am trying to open up creativity, not shut it down)- ArrayAccess can be implemented to get support for index syntax and other array like features.
If you think of more PHP features that can be useful for DSL creation, you might mention them in the comments under this question.
Please no discussion of why you think DSLs in general are good or bad. This is not intended to create extended discussion, but answers with code.
Aucun commentaire:
Enregistrer un commentaire