Lazy Models Getters (using __get())
I don't remember using PHP's magic methods too often in my apps, but I remember one situation where __get()
was very useful.
Back in the days I was developing an application in CakePHP framework that had a lot of models and all models that are used in specific controller were initialized even if method make use only of one or two of them (that's how Cake was working). So I decided to change that to lazy models to lazy (loading models when they are used for the first time).
All I did is I added a very simple __get()
function that looked for a model with specific name and loaded it. It was like 3-4 lines of code. I defined that in AppController (all CakePHP classes derives from that controller) and suddenly my app gained speed and used lower memory.
I took it further later on and also made lazy components loading in the same way.
Dynamic Model Methods (using __call())
Another good example, also from CakePHP, is how Cake searches on models. Basically you have two methods for that: find()
and findAll()
in every model, but you can also search using methods findBy<FieldName>()
and findAllBy<FieldName>()
.
In example if you have db table
notes(id, date, title, body)
And create Cake model for that. You can use methods such as findById()
, findByTitle()
and so on. You need only CamelCase db field and you can do a search on any field much quicker.
Cake does it by using __call()
magic method. This method is called if you are trying to execute a method that doesn't exists and then it just runs find()
or findAll()
with conditions dynamically created from method name and parameters. This is very simple to implement and can give you really a lot of benefits.