DEV Community

Cover image for Monolithic class in PHP
Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

Monolithic class in PHP

Let’s say you have this big fat class:

class UserService {
    public function register($data) {
        // 1. Save to DB
        // 2. Send welcome email
        // 3. Log activity
    }
}

Enter fullscreen mode Exit fullscreen mode

Refactoring Steps:

Identify different responsibilities inside the method.

Create separate classes for each responsibility.

Use Dependency Injection to connect them.

Refactored Class:

class UserService {
    private $repo;
    private $notifier;
    private $logger;

    public function __construct(UserRepository $repo, UserNotifier $notifier, UserLogger $logger) {
        $this->repo = $repo;
        $this->notifier = $notifier;
        $this->logger = $logger;
    }

    public function register($data) {
        $this->repo->create($data);
        $this->notifier->sendWelcomeEmail($data['email']);
        $this->logger->log("User registered: " . $data['email']);
    }
}

Enter fullscreen mode Exit fullscreen mode

Now, each class has one responsibility, and UserService just coordinates them.

Benefits:

Easier testing (mock only the part you need)

Easier changes (change email logic without touching DB code)

Cleaner, more maintainable code

Top comments (0)