Internal classes in PHP

Confidently refactor the internals of your library without breaking people’s code.

< back

Internal classes in PHP

If you are an open source maintainer, this article is for you. In this article, I will share a tip that made my job easier while maintaining open source libraries.

Refactoring after a stable release of your open source library can be hard, because technically in PHP: every class is public. So, if you need to create a library that provides a feature to interact with Google’s API, you would do something like this:

final class GoogleApi
{
    public function search(string $value): string
    {
        $value = StringHelper::sanitize($value);

        return /* searchResult */;
    }
}

final class StringHelper
{
    public static function sanitize(string $value): string
    {
        $value = /** sanitizedValue */;

        return $value;
    }
}

Even though the library exposes a feature to search on Google's API, it also provides the feature to sanitize a string value on the StringHelper. And, from this point, StringHelper is part of the public API of the library, and you can’t refactor without thinking that you may break people’s code.

Internal class access modifier

Maybe in the future, the PHP language will have the internal class access modifier - just like C# or Kotlin, it would prevent people from using internal classes from your library:

internal class StringHelper
{
    public static function sanitize(string $value): string {}
}

Meanwhile, the PHP @internal tag can be used to denote that the associated class/method is internal to the library. It's supported by PHPStorm and it warns people that those classes/methods are not meant to be used:

/**
 * @internal
 */
final class StringHelper
{
    public static function sanitize(string $value): string {}
}

Here is a screenshot on how it looks like on PHPStorm:

With the @internal tag, you can clearly define what classes and methods are not meant to be used by others, and at the same time, you can confidently refactor the internals of your library without breaking people’s code.

Sounds interesting? Tell me what do you think on twitter: @enunomaduro.

If you are interested in learning more about PHP, be sure subscribe to Writing Effective PHP - A video course is designed to help YOU make effective use of Modern PHP.