- 🔄 If/Else Logic Refactor
- 🔁 Loop Optimization
- 🗄 Database Query Builder
- 🛑 Error & Exception Handling
- 📦 Array & Collection Handling
- 🧩 String Handling
- ⚙️ Config & Constants
- 📝 Logging & Debug
- 💾 Caching
- 🧹 Code Cleanliness
- ✅ Quick PR Review Checklist
if ($status == 1) {
$label = 'Active';
} else if ($status == 0) {
$label = 'Inactive';
} else if ($status == 2) {
$label = 'Pending';
}$map = [
0 => 'Inactive',
1 => 'Active',
2 => 'Pending',
];
$label = $map[$status] ?? 'Unknown';$names = [];
foreach ($users as $u) {
array_push($names, $u['name']);
}$names = array_column($users, 'name');$sql = "SELECT * FROM user WHERE status = 1 AND type = 'admin'";
$users = DB::query($sql)->execute();$users = DB::select()
->from('user')
->where('status', '=', 1)
->where('type', '=', 'admin')
->execute();try {
$user = User::find($id);
} catch (Exception $e) {
echo $e->getMessage();
}try {
$user = User::find($id);
} catch (UserNotFoundException $e) {
Log::error("User not found: " . $id);
throw $e; // hoặc return response phù hợp
}$result = [];
foreach ($items as $item) {
if ($item['status'] === 'active') {
$result[] = $item;
}
}$result = array_filter($items, fn($i) => $i['status'] === 'active');if (strpos($email, '@') !== false) {
// valid email
}if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid email
}if ($status == 1) {
return 'Approved';
}const STATUS_APPROVED = 1;
if ($status == self::STATUS_APPROVED) {
return 'Approved';
}echo "Debug: ".$user->id;Log::debug('User ID', ['id' => $user->id]);$data = DB::select()->from('shop')->execute()->as_array();$data = Cache::get('shop_list');
if ($data === null) {
$data = DB::select()->from('shop')->execute()->as_array();
Cache::set('shop_list', $data, 3600);
}function process($a, $b, $c, $d, $e) {
// quá nhiều tham số
}class ProcessOptions {
public $a;
public $b;
public $c;
public $d;
public $e;
}
function process(ProcessOptions $options) {
// clean code hơn
}- 🔄 Tránh
if/elselồng nhau → dùng map/switch/guard clause - 🔁 Loop → dùng
array_map,array_filter,array_columnnế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ôngecho - 💾 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.