Rumah >pembangunan bahagian belakang >tutorial php >Gagal Cepat
Kesan dan laporkan kegagalan sebaik sahaja ia berlaku, menghalang keadaan tidak sah daripada merebak melalui sistem.
class UserRegistration { public function register(array $data): void { // Validate all inputs immediately $this->validateEmail($data['email']); $this->validatePassword($data['password']); $this->validateAge($data['age']); // Only proceed if all validations pass $this->createUser($data); } private function validateEmail(string $email): void { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new ValidationException('Invalid email format'); } if ($this->emailExists($email)) { throw new DuplicateEmailException('Email already registered'); } } }
Tujuan:
class AppConfig { private array $config; public function __construct(string $configPath) { if (!file_exists($configPath)) { throw new ConfigurationException("Config file not found: $configPath"); } $config = parse_ini_file($configPath, true); if ($config === false) { throw new ConfigurationException("Invalid config file format"); } $this->validateRequiredSettings($config); $this->config = $config; } private function validateRequiredSettings(array $config): void { $required = ['database', 'api_key', 'environment']; foreach ($required as $key) { if (!isset($config[$key])) { throw new ConfigurationException("Missing required config: $key"); } } } }
Tujuan:
class DatabaseConnection { private PDO $connection; public function __construct(array $config) { try { $this->validateDatabaseConfig($config); $this->connection = new PDO( $this->buildDsn($config), $config['username'], $config['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] ); } catch (PDOException $e) { throw new DatabaseConnectionException( "Failed to connect to database: " . $e->getMessage() ); } } private function validateDatabaseConfig(array $config): void { $required = ['host', 'port', 'database', 'username', 'password']; foreach ($required as $param) { if (!isset($config[$param])) { throw new DatabaseConfigException("Missing $param in database config"); } } } }
Tujuan:
class PaymentGateway { public function processPayment(Order $order): PaymentResult { // Validate API credentials if (!$this->validateApiCredentials()) { throw new ApiConfigurationException('Invalid API credentials'); } // Validate order before external call if (!$order->isValid()) { throw new InvalidOrderException('Invalid order state'); } try { $response = $this->apiClient->charge($order); if (!$response->isSuccessful()) { throw new PaymentFailedException($response->getError()); } return new PaymentResult($response); } catch (ApiException $e) { throw new PaymentProcessingException( "Payment processing failed: " . $e->getMessage() ); } } }
Tujuan:
class DataProcessor { public function processBatch(array $records): array { $this->validateBatchSize($records); $results = []; foreach ($records as $index => $record) { try { $this->validateRecord($record); $results[] = $this->processRecord($record); } catch (ValidationException $e) { throw new BatchProcessingException( "Failed at record $index: " . $e->getMessage() ); } } return $results; } private function validateBatchSize(array $records): void { if (empty($records)) { throw new EmptyBatchException('Empty batch provided'); } if (count($records) > 1000) { throw new BatchSizeException('Batch size exceeds maximum limit'); } } }
Tujuan:
Atas ialah kandungan terperinci Gagal Cepat. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!