Single Responsibility Principle (SRP)

In the world of software development, writing code that’s not only functional but also maintainable and adaptable is essential. Achieving this balance can be challenging, but there are principles and practices that can guide us in the right direction. One set of principles that have stood the test of time is the SOLID principles of object-oriented design. These principles, when applied correctly, help developers create code that’s easy to understand, extend, and modify.

In this blog post, we’ll explore the first SOLID principle and demonstrate its practical application in PHP using a simple example: a FileManager class.

The Single Responsibility Principle (SRP) states that a class should have only one reason to change. In other words, a class should have a single responsibility. Let’s illustrate this principle using the FileManager class as an example.

class FileManager
{
    public function readFile($filePath)
    {
        // Read file content
    }

    public function writeToFile($filePath, $data)
    {
        // Write data to the file
    }
}

At first glance, this FileManager class appears to be doing a great job – it can both read and write files. However, this dual responsibility can lead to maintenance challenges in the long run. If file reading or writing requirements change independently, you’d have to modify this class for both scenarios. This violates SRP.

Life example: We’ve been told to add support for UTF-8 BOM encoding when reading and add the capability of writing to FTP. Such FileManager class will grow rapidly and soon become unreadable.

So at the beginning, it’s okay to leave the class as is, to not overcomplicate the codebase, but later when new requirements appear, to adhere to SRP, we can split the responsibilities into two separate classes: one for reading files and another for writing files.

class FileReader
{
    public function readFile($filePath)
    {
        // Read file content
    }
}

class FileWriter
{
    public function writeToFile($filePath, $data)
    {
        // Write data to the file
    }
}

Now, we have two classes, each with a single responsibility: FileReader reads files, and FileWriter writes files. This separation aligns with SRP, making our code more maintainable and easier to modify when requirements change.

In the next section, we’ll dive into the Open-Closed Principle (OCP), showcasing how it contributes to writing robust and flexible PHP code.

Leave a Comment