CakePHP - 使用变量建模行为

发布于 2024-12-10 01:03:07 字数 118 浏览 0 评论 0原文

我希望我的两个模型继承一个属性和几个方法。我知道我可以将这些方法放入行为中,但我不确定该属性。行为是否可以具有模型继承的变量?

或者我应该创建另一个扩展 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪菊怪哟 2024-12-17 01:03:07

只要方法和变量都是公开的,您就可以将代码放入行为中。

我想,一般来说,我会追求一种行为。然后,您可以在其中创建一些默认值,并在必要时从模型中覆盖它们。另一个好处是保持代码干净:回调(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. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文