Skip to content

Instantly share code, notes, and snippets.

@tqt97
Last active August 19, 2025 15:42
Show Gist options
  • Select an option

  • Save tqt97/e6207a20feae30fa3d19f31a9d5827e4 to your computer and use it in GitHub Desktop.

Select an option

Save tqt97/e6207a20feae30fa3d19f31a9d5827e4 to your computer and use it in GitHub Desktop.

🚀 PHP/Fuel Refactor & Review Guide

📑 Table of Contents


🔄 If/Else Logic Refactor

❌ Bad

if ($status == 1) {
    $label = 'Active';
} else if ($status == 0) {
    $label = 'Inactive';
} else if ($status == 2) {
    $label = 'Pending';
}

✅ Good

$map = [
    0 => 'Inactive',
    1 => 'Active',
    2 => 'Pending',
];

$label = $map[$status] ?? 'Unknown';

🔁 Loop Optimization

❌ Bad

$names = [];
foreach ($users as $u) {
    array_push($names, $u['name']);
}

✅ Good

$names = array_column($users, 'name');

🗄 Database Query Builder

❌ Bad

$sql = "SELECT * FROM user WHERE status = 1 AND type = 'admin'";
$users = DB::query($sql)->execute();

✅ Good

$users = DB::select()
    ->from('user')
    ->where('status', '=', 1)
    ->where('type', '=', 'admin')
    ->execute();

🛑 Error & Exception Handling

❌ Bad

try {
    $user = User::find($id);
} catch (Exception $e) {
    echo $e->getMessage();
}

✅ Good

try {
    $user = User::find($id);
} catch (UserNotFoundException $e) {
    Log::error("User not found: " . $id);
    throw $e; // hoặc return response phù hợp
}

📦 Array & Collection Handling

❌ Bad

$result = [];
foreach ($items as $item) {
    if ($item['status'] === 'active') {
        $result[] = $item;
    }
}

✅ Good

$result = array_filter($items, fn($i) => $i['status'] === 'active');

🧩 String Handling

❌ Bad

if (strpos($email, '@') !== false) {
    // valid email
}

✅ Good

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // valid email
}

⚙️ Config & Constants

❌ Bad

if ($status == 1) {
    return 'Approved';
}

✅ Good

const STATUS_APPROVED = 1;

if ($status == self::STATUS_APPROVED) {
    return 'Approved';
}

📝 Logging & Debug

❌ Bad

echo "Debug: ".$user->id;

✅ Good

Log::debug('User ID', ['id' => $user->id]);

💾 Caching

❌ Bad

$data = DB::select()->from('shop')->execute()->as_array();

✅ Good

$data = Cache::get('shop_list');
if ($data === null) {
    $data = DB::select()->from('shop')->execute()->as_array();
    Cache::set('shop_list', $data, 3600);
}

🧹 Code Cleanliness

❌ Bad

function process($a, $b, $c, $d, $e) {
    // quá nhiều tham số
}

✅ Good

class ProcessOptions {
    public $a;
    public $b;
    public $c;
    public $d;
    public $e;
}

function process(ProcessOptions $options) {
    // clean code hơn
}

✅ Quick PR Review Checklist

  • 🔄 Tránh if/else lồng nhau → dùng map/switch/guard clause
  • 🔁 Loop → dùng array_map, array_filter, array_column nếu có thể
  • 🗄 Query → luôn dùng Query Builder thay vì hardcode SQL
  • 🛑 Exception → throw loại cụ thể, log error rõ ràng
  • 📦 Array → tránh array_push, dùng []
  • 🧩 String → dùng filter_var, mb_* cho Unicode
  • ⚙️ Config → không hardcode, dùng Config::get() hoặc constants
  • 📝 Logging → dùng Log::debug/info/error, không echo
  • 💾 Cache → thêm cache layer cho query nặng, tránh query lặp
  • 🧹 Function → không quá nhiều tham số, refactor thành class/DTO
  • 📏 Code style → PSR-12, spacing rõ ràng
  • 🔒 Security → escape input/output, validate dữ liệu
  • 🧪 Test → thêm unit test cho logic phức tạp
  • 📖 Comment → viết PHPDoc rõ cho function/class
  • 🧭 Naming → đặt tên biến, hàm rõ nghĩa, tránh viết tắt khó hiểu
🎯 Mục tiêu ❌ Bad ✅ Good
Không hardcode query $res = DB::query("SELECT * FROM user WHERE id=$id")->execute(); DB::select()->from('user')->where('id', $id)->execute();
Validate input $age = $_POST['age']; $age = Input::post('age'); Validation::forge()->add('age','Age')->add_rule('valid_string', ['numeric']);
Handle lỗi $res = DB::select()->from('user')->execute(); try {...} catch (Database_Exception $e) { Log::error($e->getMessage()); throw new HttpServerErrorException('DB Error'); }
Transaction DB::query("INSERT ..."); DB::query("UPDATE ..."); DB::start_transaction(); try {... DB::commit_transaction(); } catch (Exception $e) { DB::rollback_transaction(); }
Logging echo $e->getMessage(); Log::error('Payment failed: '.$e->getMessage());
Không lặp code if($a==1){...} if($a==2){...} switch($a){ case 1: ...; break; case 2: ...; }
Caching query DB::select()->from('user')->execute(); Cache::get_or_set('users.active', fn()=>DB::select()->from('user')->where('status',1)->execute(), 300);
Check null/isset $name = $arr['name']; $name = $arr['name'] ?? '';
Strict typing function sum($a,$b){return $a+$b;} function sum(int $a, int $b): int { return $a + $b; }
Không throw lung tung throw new Exception("err"); throw new DomainException("Invalid user state");
Input sanitize echo $_GET['q']; echo Security::htmlentities(Input::get('q'));

👉 Với mỗi PR, hãy chạy checklist trên. Nếu 2–3 case bị dính → cần refactor trước khi merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment