Articles

Refactoring PHP

ยท 19 min readCoding

I've been programming in PHP now for almost ten years, and if there is one thing I learned over this period, it's that readability and simplicity are the keys for maintainable and sustainable code. Every first attempt to write code should be about making it work. Only after that, you should take some time to refactor. This is when I aim for readability and simplicity. Today I see refactoring as one of my main skills. In this post, I share with you my refactoring practices for PHP.

Refactoring is the process of modifying and restructuring code without changing its functionality. When I first heard about it, I was like: Why would anyone do that? It took some years until I fully understood the concept and that the working code is not always good. So with refactoring, you can make working code better, and what better means is something developers will argue for hours. In the end, you have to define it for yourself.

Stage 1#1 - Be Expressive

This might be an easy tip, but writing expressive code can improve it a lot. Always make your code self-explaining so that you, your future self or any other developers who stumble over your code knows what is going on.

But then developers also say naming is one of the hardest things in programming. This is one reason why this is not as easy as it sounds. ๐Ÿคทโ€

Note: Make sure to hit the "Show/Hide Notes" buttons on the code examples to get details about why we needed to change the code.

Example #1 - Naming

PHP
$status = $user->status('pending');
B: top ยท A: copyB

Example #2 - Naming

PHP
return $factory->getTargetClass();
B: top ยท A: copyB

Example #3 - Extracting

PHP
public function setCodeExamples(string $exampleBefore, string $exampleAfter)
{
$this->exampleBefore = file_get_contents(base_path("$exampleBefore.md"));
$this->exampleAfter = file_get_contents(base_path("$exampleAfter.md"));
}
B: top ยท A: copyB

Example #4 - Extracting

PHP
User::whereNotNull('subscribed')->where('status', 'active');
B: top ยท A: copyB

Example #5 - Extracting

This is an example of one of my projects from last year. We had a command-line command to import users. The class ImportUsersCommand contains a handle method to perform the tasks.

PHP
protected function handle()
{
$url = $this->option('url') ?: $this->ask('Please provide the URL for the import:');
$importResponse = $this->http->get($url);
$bar = $this->output->createProgressBar($importResponse->count());
$bar->start();
$this->userRepository->truncate();
collect($importResponse->results)->each(function (array $attributes) use ($bar) {
$this->userRepository->create($attributes);
$bar->advance();
});
$bar->finish();
$this->output->newLine();
$this->info('Thanks. Users have been imported.');
if($this->option('with-backup')) {
$this->storage
->disk('backups')
->put(date('Y-m-d').'-import.json', $response->body());
$this->info('Backup was stored successfully.');
}
}
B: top ยท A: copyB

Stage 2#2 - Return Early

The concept of early returns refers to a practice where we try to avoid nesting by breaking a structure down to specific cases. In return, we will get a more linear code, which is much easier to read and grasp. Every case is separated and good to follow. Don't be afraid of using multiple return statements.

Example #1

PHP
public function calculateScore(User $user): int
{
if ($user->inactive) {
$score = 0;
} else {
if ($user->hasBonus) {
$score = $user->score + $this->bonus;
} else {
$score = $user->score;
}
}
return $score;
}
B: top ยท A: copyB

Example #2

PHP
public function sendInvoice(Invoice $invoice): void
{
if($user->notificationChannel === 'Slack')
{
$this->notifier->slack($invoice);
} else {
$this->notifier->email($invoice);
}
}
B: top ยท A: copyB
Note: You sometimes also hear the term "guard-clauses" which is what you can achieve with early returns. You are guarding your method from special conditions.

Stage 3#3 - Refactor To Collections

In PHP, we work a lot with arrays of different data. The available features to handle and transform those arrays are quite limited in PHP and don't provide a good experience. (array_walk, usort, etc.)

To tackle this problem, there is this concept of Collection classes, which help you handle arrays. Most known is the implementation in Laravel, where a collection class provides you with dozens of useful features to work with arrays.

Note: For the following examples, I will use Laravel's collect() helper, but the approach is very similar with other available collection classes from other frameworks or libraries.

Example #1

PHP
$score = 0;
foreach($this->playedGames as $game) {
$score += $game->score;
}
return $score;
B: top ยท A: copyB

Example #2

PHP
$users = [
[ 'id' => 801, 'name' => 'Peter', 'score' => 505, 'active' => true],
[ 'id' => 844, 'name' => 'Mary', 'score' => 704, 'active' => true],
[ 'id' => 542, 'name' => 'Norman', 'score' => 104, 'active' => false],
];
// Requested Result: only active users, sorted by score ["Mary(704)","Peter(505)"]
$users = array_filter($users, fn ($user) => $user['active']);
usort($users, fn($a, $b) => $a['score'] < $b['score']);
$userHighScoreTitles = array_map(fn($user) => $user['name'] . '(' . $user['score'] . ')', $users);
return $userHighScoreTitles;
B: top ยท A: copyB
Note: Adam Wathan wrote a book about how to use collections to never write a loop again which I can highly recommend.

Stage 4#4 - Consistency

Every line of code adds a little amount of visual noise. The more code, the more difficult it gets to read. This is why it is essential to set rules. Keeping similar things consistent will help you recognize code and patterns. It will result in less noise and more readable code.

Example #1

PHP
class UserController
{
public function find($userId)
{
}
}
class InvoicesController
{
public function find($user_id) {
}
}
B: top ยท A: copyB

Example #2

PHP
class PdfExporter
{
public function handle(Collection $items): void
{
// export items...
}
}
class CsvExporter
{
public function export(Collection $items): void
{
// export items...
}
}
$pdfExport->handle();
$csvExporter->export();
B: top ยท A: copyB

Refactoring โค๏ธ Tests

I already mentioned that refactoring doesn't change the functionality of your code. This comes handy when running tests, because they should work after refactoring too. This is why I only start to refactor my code, when there are tests. They will assure that I don't unintentionally change the behaviour of my code. So don't forget to write tests or even go TDD.

Conclusion

This is how I refactor PHP. In the end, you and your team have to decide how you want your code to be. Just make sure to define it, write it down, and save enough time to make it happen after your code is working. I started with my main principles and I plan to cover more topics soon. If you have refactoring tips you'd like to share, just ping me on Twitter.