---
title: Centralize Constants
impact: HIGH
impactDescription: makes values easy to find, update, and manage
tags: constants, magic-numbers, configuration, quality, php
---

## Centralize Constants

Magic numbers or strings scattered throughout the codebase are difficult to maintain and understand. Centralizing constants in classes or using Enums makes the code self-documenting and provides a single source of truth.

**Incorrect (magic values):**

```php
if (strlen($password) < 8) { ... }
if ($retryCount > 3) { ... }
if ($order->status === 1) { ... }
sleep(300); // 5 minutes? 
if ($user->role === 'admin') { ... }
```

**Correct (centralized constants and Enums):**

```php
/**
 * Using Class Constants
 */
class AuthConfig {
    public const PASSWORD_MIN_LENGTH = 8;
    public const MAX_RETRY_ATTEMPTS = 3;
    public const SESSION_TIMEOUT_SECONDS = 300;
}

/**
 * Using PHP 8.1+ Enums (Recommended for categories)
 */
enum OrderStatus: int {
    case PENDING = 1;
    case APPROVED = 2;
    case SHIPPED = 3;
}

enum UserRole: string {
    case ADMIN = 'admin';
    case USER = 'user';
}

// Usage
if (strlen($password) < AuthConfig::PASSWORD_MIN_LENGTH) { ... }
if ($order->status === OrderStatus::PENDING->value) { ... }
if ($user->role === UserRole::ADMIN->value) { ... }
```

**Benefits:**
- **Searchability**: Find all usages of a constant instantly.
- **Self-Documentation**: `MAX_RETRY_ATTEMPTS` is clearer than `3`.
- **Consistency**: Prevents typos (e.g., `'admn'` vs `'admin'`).
- **Refactoring**: Change a value in one place to update the entire application.

**Tools:** PHPStan (disallow magic numbers), Psalm, PR review
