1

I am using cakephp 3.x

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?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

1 Answers1

6

This sounds like you have no idea when and why you use the visibility scope. See this question "What is the difference between public, private, and protected?" as well.

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.

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.

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.

Community
  • 1
  • 1
floriank
  • 25,546
  • 9
  • 42
  • 66