MVC Model get() and set() vs. straight-up $model->var = val
When is the right time to use functions to set variables inside of my models, verse simply directly assigning them?
AKA...
When do I use:
$model->set('status','active');
...instead of:
$开发者_如何学Pythonmodel->status = 'active';
using getters and setters is good for the encapsulation of code. It's always a good idea to use them.
Think about this:
- What if your model has some variables that you don't want to be able to be read or changed (or both)?
- What if you ever need to do something besides just getting and setting the variable? (for example, sanatizing data)?
If you're using a recent version of PHP (5.x), you can get the best of both worlds with the magic methods __get()
and __set()
. (PHP reference). Any access to an undefined property will be routed to the appropriate get/set function automatically.
I must admin that I'm not certain if this is really a good idea to use or not, but it seems like a decent fit for a base model class in a MVC system.
精彩评论