Home Backend Development PHP Tutorial Teach you how to refactor PHP code better

Teach you how to refactor PHP code better

Mar 13, 2023 pm 03:44 PM
php

This article brings you relevant knowledge about PHP, and mainly talks about what is refactoring? How to better refactor PHP code? Friends who are interested can take a look below. I hope it will be helpful to everyone.

Teach you how to refactor PHP code better

Refactoring refers to modifying or rewriting the code without changing the original functionality.

In the following examples, I will show you how to write better code.

#1 - Expressiveness

This may just be a simple tip, but writing expressive code can greatly improve our code. Always make the code self-explanatory so that future you or other developers can know what is going on in the code.

However, some developers say that naming is one of the most difficult things in programming. That's one reason why it's not as easy as it sounds.

Example #1 - Naming

Before

// ❌ 这个方法是用来做什么的,方法名表达并不清晰
// ❌ 是设置状态还是检查状态呢?
$status = $user->status('pending');
Copy after login

After

// ✅ 通过添加 is,使方法名表达的意图更清晰
// ✅ 检测用户状态是否与给定状态相等
// ✅ 同时新变量名让我们可以推断它是布尔值
$isUserPending = $user->isStatus('pending');
Copy after login

Example #2 - Naming

before

// ❌ 这个类返回的是什么?类名?类全名?还是类路径?
return $factory->getTargetClass();
Copy after login

after

// ✅ 我们获取的是类路径
// ✅ 如果用户想要类名?则找错了方法
return $factory->getTargetClassPath();
Copy after login

Example #3 - Extract

before

// ❌ 重复的代码 ( "file_get_contents", "base_path" 方法以及文件扩展)
// ❌ 此刻,我们不去关心如何获得code examples
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"));
}
Copy after login

after

public function setCodeExamples(string $exampleBefore, string $exampleAfter)
{ 
    // ✅ 代码直接说明了我们的意图:获取code example(不关注如何获取)
    $this->exampleBefore = $this->getCodeExample($exampleBefore);
    $this->exampleAfter = $this->getCodeExample($exampleAfter);
}
// ✅ 这个新方法可多次调用
private function getCodeExample(string $exampleName): string
{
    return file_get_contents(base_path("$exampleName.md"));
}
Copy after login

Example #4 - Extract

Before

// ❌ 多重 where 语句,使阅读变得困难
// ❌ 意图究竟是什么呢?
User::whereNotNull('subscribed')->where('status', 'active');
Copy after login

After

// ✅ 这个新的scope方法说明了发生了什么事
// ✅ 如果我们需要了解更多细节,可以进入这个scope方法内部去了解
// ✅ "subscribed" scope 方法可在其他地方使用
User::subscribed();
Copy after login

Example #5 - Extract

This is an example from my previous project. We use the command line to import users. The ImportUsersCommand class contains a handle method to handle tasks.

Before

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.');
    }
}
Copy after login

After

protected function handle(): void
{
    // ✅ handle方法是你访问该类首先会查看的方法
    // ✅ 现在可以很容易就对这个方法做了些什么有个粗略的了解
    $url = $this->option('url') ?: $this->ask('Please provide the URL for the import:');
    $importResponse =  $this->http->get($url);
    $this->importUsers($importResponse->results);
    $this->saveBackupIfAsked($importResponse);
}
// ✅ 如果需要了解更多细节,可以查看这些专用的方法
protected function importUsers($userData): void
{
    $bar = $this->output->createProgressBar(count($userData));
    $bar->start();
    $this->userRepository->truncate();
    collect($userData)->each(function (array $attributes) use ($bar) {
        $this->userRepository->create($attributes);
        $bar->advance();
    });
    $bar->finish();
    $this->output->newLine();
    $this->info('Thanks. Users have been imported.');
}
// ✅ 不要害怕使用多行代码
// ✅ 这个例子中它让我们核心的 handle 方法更为简洁
protected function saveBackupIfAsked(Response $response): void
{
    if($this->option('with-backup')) {
        $this->storage
            ->disk('backups')
            ->put(date('Y-m-d').'-import.json', $response->body());
        $this->info('Backup was stored successfully.');
    }
}
Copy after login

#2 - Early return

Early return means that we try to pass the structure Decompose into specific cases to avoid nesting. This way we get a more linear code that is easier to read and understand. Don't be afraid to use multiple return statements.

Example#1

Before

public function calculateScore(User $user): int
{
    if ($user->inactive) {
        $score = 0;
    } else {
        // ❌ 怎么又有一个 "if"?
        if ($user->hasBonus) {
            $score = $user->score + $this->bonus;
        } else {
            // ❌ 由于存在多个层级,大费眼神 ? 
            $score = $user->score;
        }
    }
    return $score;
}
Copy after login

After

public function calculateScore(User $user): int
{
    // ✅ 边缘用例提前检测
    if ($user->inactive) {
        return 0;
    }
    // ✅ 每个用例都有自己的代码块,使得更容易跟进
    if ($user->hasBonus) {
        return $user->score + $this->bonus;
    }
    return $user->score;
}
Copy after login

Example#2

Before

public function sendInvoice(Invoice $invoice): void
{
    if($user->notificationChannel === 'Slack')
    {
        $this->notifier->slack($invoice);
    } else {
        // ❌ 即使是简单的ELSE都影响代码的可读性
        $this->notifier->email($invoice);
    }
}
Copy after login

After

public function sendInvoice(Invoice $invoice): bool
{
    // ✅ 每个条件都易读
    if($user->notificationChannel === 'Slack')
    {
        return $this->notifier->slack($invoice);
    }
    // ✅ 不用再考虑ELSE 指向哪里
    return $this->notifier->email($invoice);
}
Copy after login

Note: Sometimes you will hear the term "defense statement", which is implemented by returning early.

#3 - Reconstruct into a collection Collection

In PHP, we use arrays in many different data. The functionality available for handling and converting these arrays is very limited and does not provide a good experience. (array_walk, usort, etc)

To deal with this problem, there is a concept of Collection class that can be used to help you deal with arrays. The best known implementation is in Laravel, where the collection class provides many useful features for working with arrays.

Note: In the following examples, I will use Laravel's collect () helper function, but it can be used in similar ways in other frameworks or libraries.

Example#1

Before

// ❌ 这里我们有一个临时变量 
$score = 0;
// ❌ 用循环没有问题,不过可读性还是有改善空间
foreach($this->playedGames as $game) {
    $score += $game->score;
}
return $score;
Copy after login

After

// ✅ 集合是带有方法的对象
// ✅ sum 方法使之更具表现力
return collect($this->playedGames)
    ->sum('score');
Copy after login

Example#2

Before

$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],
];
// 请求结果: 只显示活跃用户,以 score 排序  ["Mary(704)","Peter(505)"]
$users = array_filter($users, fn ($user) => $user['active']);
// ❌ usort 进行排序处理的又是哪一个对象呢?它是如何实现?
usort($users, fn($a, $b) => $a[&#39;score&#39;] < $b[&#39;score&#39;]);
// ❌ 所有的转换都是分离的,不过都是users相关的
$userHighScoreTitles = array_map(fn($user) => $user[&#39;name&#39;] . &#39;(&#39; . $user[&#39;score&#39;] . &#39;)&#39;, $users);
return $userHighScoreTitles;
Copy after login

After

$users = [
    [ &#39;id&#39; => 801, &#39;name&#39; => &#39;Peter&#39;, &#39;score&#39; => 505, &#39;active&#39; => true],
    [ &#39;id&#39; => 844, &#39;name&#39; => &#39;Mary&#39;, &#39;score&#39; => 704, &#39;active&#39; => true],
    [ &#39;id&#39; => 542, &#39;name&#39; => &#39;Norman&#39;, &#39;score&#39; => 104, &#39;active&#39; => false],
];
// 请求结果: 只显示活跃用户,以 score 排序  ["Mary(704)","Peter(505)"]
// ✅ 只传入一次users
return collect($users)
    // ✅ 我们通过管道将其传入所有方法
  ->filter(fn($user) => $user[&#39;active&#39;])
  ->sortBy(&#39;score&#39;)
  ->map(fn($user) => "{$user[&#39;name&#39;]} ({$user[&#39;score&#39;]})"
  ->values()
    // ✅ 最后返回数组
  ->toArray();
Copy after login

#4 - Consistency

Every line of code adds a small amount of visual noise. The more code there is, the harder it is to read. That's why it's important to have rules. Keeping things like this consistent will help you recognize codes and patterns. This will result in less noise and more readable code.

Example#1

Before

class UserController 
{
    // ❌ 确定如何命名变量(驼峰或是蛇形等),不要混用!
    public function find($userId)
    {
    }
}
// ❌ 选择使用单数或者复数形式命名控制器,并保持一致
class InvoicesController 
{
    // ❌ 修改了样式,如花扣号的位置,影响可读性
    public function find($user_id) {
    }
}
Copy after login

After

class UserController 
{
    // ✅ 所有变量驼峰式命名
    public function find($userId)
    {
    }
}
// ✅ 控制器命名规则一致(此处都使用单数)
class InvoiceController 
{
    // ✅ 花括号的位置(格式)一致,使代码更为可读
    public function find($userId)
    {
    }
}
Copy after login

Example#2

Before

class PdfExporter
{
    // ❌ "handle" 和 "export" 是类似方法的不同名称
    public function handle(Collection $items): void
    {
        // export items...
    }
}
class CsvExporter
{
    public function export(Collection $items): void
    {
        // export items...
    }
}
// ❌ 使用时你会疑惑它们是否处理相似的任务
// ❌ 你可能需要再去查看类源码进行确定
$pdfExport->handle();
$csvExporter->export();
Copy after login

After

// ✅ 可通过接口提供通用规则保持一致性
interface Exporter
{
    public function export(Collection $items): void;
}
class PdfExporter implements Exporter
{
    public function export(Collection $items): void
    {
        // export items...
    }
}
class CsvExporter implements Exporter
{
    public function export(Collection $items): void
    {
        // export items...
    }
}
// ✅ 对类似的任务使用相同的方法名,更具可读性
// ✅ 不用再去查看类源码,变可知它们都用在导出数据
$pdfExport->export();
$csvExporter->export();
Copy after login

Refactoring❤️ Testing

I have already mentioned that refactoring does not change the functionality of the code. This is convenient when running tests, as they should also work after refactoring. That's why I only start refactoring code when I have tests. They will ensure that I don't inadvertently change the behavior of the code. So don’t forget to write tests and even go for TDD.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Teach you how to refactor PHP code better. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1251
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles