CakePHP - Model behaviours with variables

2019-08-30 17:59发布

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条回答
我命由我不由天
2楼-- · 2019-08-30 18:50

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.

查看更多
登录 后发表回答