5

I come from a Java background and I have been working with PHP for almost a year now. I have worked with WordPress, Zend and currently I'm using CakePHP. I was going through Cake's lib and I couldn't help notice that Cake goes a long way avoiding the "private" access specifier. Cake says

Try to avoid private methods or variables, though, in favor of protected ones. The latter can be accessed or modified by subclasses, whereas private ones prevent extension or re-use.

in this tutorial.

Why does Cake overly shun the "private" access specifier while good OO design encourages its use i.e to apply the most restrictive visibility for a class member that is not intended to be part of its exported API? I'm willing to believe that "private" functions are difficult test, but is rest of the convention justified outside Cake? or perhaps it's just a Cake convention of OO design geared towards extensibility at the expense of being a stickler for stringent (or traditional?) OO design?

1 Answers1

12

The PHP world is full of bad advice, and your quote is yet another example of it. CakePHP is an entry level framework, and its documentation is written with less experienced developers in mind. That, however, doesn't justify so naive a statement, especially in the framework's official documentation.

Whether you'll use private or protected is a design choice. If there's no reason for your properties and functions to be inherited, use private. If, on the other hand, your design calls for those properties and functions to be available to subclasses, use protected.

It really is as simple as that.

yannis
  • 39,547
  • 40
  • 183
  • 216
  • Thanks for clarifying that, it's confusing seeing a method or field being declared `protected` without any prospect of it being used in a subclass whatsoever. – Tafadzwa Gonera Oct 18 '13 at 10:00
  • 1
    @Tifa You're welcome. PHP adopted Java's object model and although there are a few implementation differences, as you get more familiar with PHP you'll find out that there's little reason to make different design choices in PHP than the ones you are used to making in Java. Unfortunately, proper documentation isn't one of the ecosystem's stronger points. When something feels out of place, as with Cake's conventions, don't hesitate to dig a bit deeper and challenge the "official" docs. – yannis Oct 18 '13 at 10:05
  • 1
    I have seen this idea in quite a number of places in the PHP world. And finally decided that it is really bad advice. The simple problem is, if you change a protected method or property, you break code that uses your library and calls or overrides this method. If you change a private method or property, this won't happen. – donquixote Jul 09 '14 at 03:11