Milk Admin

File Class

Revision: 2025-11-11

Thread-safe file operations with mandatory locking and exception-based error handling.

Exception Handling

All methods throw exceptions on errors:

  • FileException - File access, permission, or I/O errors

Lock Management

  • Shared locks (LOCK_SH): Read operations, allow concurrent reads
  • Exclusive locks (LOCK_EX): Write operations, block all access
  • Retry mechanism: 200 attempts × 50ms = 10-second timeout

Methods

getContents(string $file_path) : string

Reads file content with shared lock.

try {
    $content = File::getContents('config.json');
    $config = json_decode($content, true);
} catch (\App\Exceptions\FileException $e) {
    echo "Read failed: " . $e->getMessage();
}

putContents(string $file_path, string $data) : void

Writes data with exclusive lock, creating or overwriting file.

try {
    $data = ['user' => 'john', 'time' => time()];
    File::putContents('data.json', json_encode($data));
} catch (\App\Exceptions\FileException $e) {
    echo "Write failed: " . $e->getMessage();
}

appendContents(string $file_path, string $data) : void

Appends data with exclusive lock.

try {
    $log = date('Y-m-d H:i:s') . " - User logged in\n";
    File::appendContents('app.log', $log);
} catch (\App\Exceptions\FileException $e) {
    error_log("Log failed: " . $e->getMessage());
}

Examples

Thread-Safe Configuration Manager

use App\Exceptions\FileException;

class ConfigManager {
    private string $file;

    public function __construct(string $file) {
        $this->file = $file;
    }

    public function load(): array {
        try {
            $json = File::getContents($this->file);
            return json_decode($json, true) ?: [];
        } catch (FileException $e) {
            // Return empty config on error
            return [];
        }
    }

    public function update(string $key, mixed $value): void {
        $config = $this->load();
        $config[$key] = $value;
        $json = json_encode($config, JSON_PRETTY_PRINT);
        File::putContents($this->file, $json);
    }
}

// Usage
$config = new ConfigManager('app_config.json');

try {
    $config->update('last_updated', time());
    $config->update('version', '2.0');
    echo "Configuration updated";
} catch (FileException $e) {
    echo "Update failed: " . $e->getMessage();
}
Loading...