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
}
}

Refactoring Steps:

Identify different responsibilit…


This content originally appeared on DEV Community and was authored by Ahmed Raza Idrisi

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
    }
}

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']);
    }
}

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


This content originally appeared on DEV Community and was authored by Ahmed Raza Idrisi


Print Share Comment Cite Upload Translate Updates
APA

Ahmed Raza Idrisi | Sciencx (2025-08-14T08:35:14+00:00) Monolithic class in PHP. Retrieved from https://www.scien.cx/2025/08/14/monolithic-class-in-php/

MLA
" » Monolithic class in PHP." Ahmed Raza Idrisi | Sciencx - Thursday August 14, 2025, https://www.scien.cx/2025/08/14/monolithic-class-in-php/
HARVARD
Ahmed Raza Idrisi | Sciencx Thursday August 14, 2025 » Monolithic class in PHP., viewed ,<https://www.scien.cx/2025/08/14/monolithic-class-in-php/>
VANCOUVER
Ahmed Raza Idrisi | Sciencx - » Monolithic class in PHP. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/08/14/monolithic-class-in-php/
CHICAGO
" » Monolithic class in PHP." Ahmed Raza Idrisi | Sciencx - Accessed . https://www.scien.cx/2025/08/14/monolithic-class-in-php/
IEEE
" » Monolithic class in PHP." Ahmed Raza Idrisi | Sciencx [Online]. Available: https://www.scien.cx/2025/08/14/monolithic-class-in-php/. [Accessed: ]
rf:citation
» Monolithic class in PHP | Ahmed Raza Idrisi | Sciencx | https://www.scien.cx/2025/08/14/monolithic-class-in-php/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.