问题
I want two of my models to inherit a property and a couple of methods. I know I could put the methods in a behaviour but I'm not sure about the property. Can a behaviour have variables that are inherited by the model?
Or should I just create another model that extends AppModel, and have the two models extend that one?
回答1:
As long as both methods and variables are made public you can put your code into a behavior.
In general I would go for a behavior, I guess. You could then create some defaults in it and override them later from the Models if necessary. Another benefit is that you keep your code clean: callbacks (beforeSave
, etc.) are ran by the models having the behavior attached and do not clutter your model code like a parent model would (you would need e.g. a parent::beforeSave()
when you add callbacks to your models and still want the callbacks to run from the parent model class.
If you provide more information, maybe we can give you a more specific answer.
来源:https://stackoverflow.com/questions/7793630/cakephp-model-behaviours-with-variables