为什么cakephp 3.x控制器和表中的函数公开但实体中的函数受保护? [英] Why are functions in cakephp 3.x controllers and tables public but functions in entities protected?

查看:146
本文介绍了为什么cakephp 3.x控制器和表中的函数公开但实体中的函数受保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用cakephp 3.x

I am using cakephp 3.x

我做了这个观察。控制器和表中的函数声明为public。实体中的函数声明为protected。为什么不能将实体函数声明为public?

I made this observation. Functions in controllers and tables are declared as public. Functions in entities are declared as protected. Why can't entities functions be declared as public as well?

推荐答案

这听起来像你不知道什么时候, 可见性范围。请参阅此问题 PHP:公共,私人,受保护

This sounds like you have no idea when and why you use the visibility scope. See this question "PHP: Public, Private, Protected" as well.

事实上,没有什么能阻止你在一个实体中声明一个公共方法,试试它。没有什么能阻止你在其他类中使用protected和private。但使用它们在有意义的建筑智慧。 实体已拥有公共方法。我建议您阅读有关图书中实体的章节,详细说明实体如何工作,它们是什么以及他们想要什么,以及您可以使用它们做什么。

In fact nothing prevents you from declaring a public method in an entity, try it. Nothing prevents you from using protected and private in other classes as well. But use them where it makes sense architecture wise. Also entities already have public methods. I suggest you to read the chapter about entities in the book, it explains in detail how entities work, what they are and what they're thought for and what you can do with them.

实体表示数据,数据通过属性访问或者像数组一样,因为对象实现了 ArrayAccess 。要访问虚拟属性(再次阅读本章),使用访问器和mutator,它们实际上是受保护的。当您尝试访问非现有属性时,会调用这些方法,查看get()方法。它们受到保护,因为不希望直接访问它们,它将打破实体的工作方式。数据被认为只能通过属性或get()方法访问,这样所有实体都可以工作。

Entities represent data, the data is accessed through the properties or like an array because the object implements ArrayAccess. To access virtual properties (again, read the chapter) the accessors and mutators are used, which are in fact protected. These methods get called when you try to access a non existing property, see the get() method. They're protected because direct access to them is not desired, it would break the way the entities work. Data is thought to be accessed only through the properties or the get() method so that all entities everywhere work the same.

在良好的代码中,原因。但我已经看到坏的代码,人们使事情私人的疯狂没有理由,这有效地防止你通过继承它们改变对象的行为。我没有检查,但我很确定你不会在框架中找到一个私有方法,因为它被认为是扩展。

In well written code the visibility scope usually has a reason. But I've seen bad code where people made things private like crazy without reason, which effectively prevents you from altering the objects behaviour by inheriting them. I haven't checked but I'm pretty sure you won't find a private method in the framework because it is thought to be extended.

底线:Analzye代码,并了解为什么某些东西被保护,如果你喜欢知道它。这将是一个不同的原因,不同情况。

Bottom line: Analzye the code and get an understanding of why something is protected if you like to know it. It will be for a different reason from case to case.

这篇关于为什么cakephp 3.x控制器和表中的函数公开但实体中的函数受保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆