Question

I need some classes to befriend other classes in my system. Lack of this feature made me publicize some methods which shouldn't be public. The consequences of that are that members of my team implement code in a bad and ugly way which causes a mess.

Is there a way to define a friendship in php 5.3?

(I am aware of http://bugs.php.net/bug.php?id=34044 You might want to vote there if there is no simple solution).

Was it helpful?

Solution

In short, no. The generally accepted approach is to either educate your team on how to develop against your libraries or redesign. The first solution can be done quite easily by building docs with phpdoc and setting the visibility in the docbloc comments with @visibility, and of course actually documenting the classes. The second I wouldn't be able to comment on without knowing a little more detail.

/**
 * Some helper class for LibraryInterface
 *
 * ATTENTION!
 * This class should not be used outside this package.
 *
 * @visibility package
 * @package mypackage
 */
class Helper
{
  public function doStuff()
  {
    /* does stuff */
  }
}

/**
 * Class for accessing some part of the library.
 *
 * @visibility public
 * @package mypackage
 */
class LibraryInterface
{
  public function doStuff()
  {
    $this->helper->doStuff();
  }
}

OTHER TIPS

I was seeking the same functionality and was able to implement a solution. To use it, just derive from class Friendship and specify the classes that are friends of your derived class. You can find it here: http://rommelsantor.com/clog/2011/04/23/php-5-3-class-friendship-support

I'm not sure what you mean by "befriend". You can use abstract classes, in which any new class can "implement" that class. Or you can have classes extend other classes and make the methods, variables, etc "protected" as opposed to public or private.

If your team implements any code "in a bad and ugly way", then you may have bigger problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top