CakePHP - 使用变量建模行为
我希望我的两个模型继承一个属性和几个方法。我知道我可以将这些方法放入行为中,但我不确定该属性。行为是否可以具有模型继承的变量?
或者我应该创建另一个扩展 AppModel 的模型,并让这两个模型扩展该模型?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要方法和变量都是公开的,您就可以将代码放入行为中。
我想,一般来说,我会追求一种行为。然后,您可以在其中创建一些默认值,并在必要时从模型中覆盖它们。另一个好处是保持代码干净:回调(
beforeSave
等)由附加行为的模型运行,并且不会像父模型那样混乱您的模型代码(您需要例如parent::beforeSave()
当您向模型添加回调并且仍然希望回调从父模型类运行时。如果您提供更多信息,也许我们可以为您提供更具体的答案。
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. aparent::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.