How-to's SOLID: The 5 Principles of Object Oriented Design
The Single Responsibility Principle states:
Class should have only one reason to change.
This mean that the class should be responsible for a single task, ensuring it stay focused and cohesive. This make the class easier to maintain and modify without affecting other functionality. Bad
class SMS
{
  public function __construct(
    public string $from,
    public string $to,
    public string $body,
  ) { }

  public function send(Message $message): void
  {
    // Send the SMS message using third-party SMS provider (e.g., AWS SNS, Twilio, Vonage)
  }
}
Good
Playground (Tinker)
class Message
{
  public function __construct(
    public string $from,
    public string $to,
    public string $body,
  ) { }
}

class SMSService
{
  public function send(Message $message): void
  {
    // Send the SMS message using third-party SMS provider (e.g., AWS SNS, Twilio, Vonage)
  }
}
  • Message class represent the structure of an SMS message. Its role is to hold the data (such as sender, recipient, and message body) without being concerned with how or where it will be used.
  • SMSService class is responsible for sending the SMS message using a third-party provider. It only accept an already created Message instance and send it.