alizharb / php85-safe-api-client
A robust API client demonstrating PHP 8.5's #[NoDiscard] attribute for safe response handling.
Installs: 0
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/alizharb/php85-safe-api-client
Requires
- php: >=8.5
Requires (Dev)
- phpunit/phpunit: ^11.0
README
A robust API client demonstrating PHP 8.5's #[\NoDiscard] attribute for safe response handling.
๐ Introduction
In API integrations, ignoring a response often means ignoring an error.
PHP 8.5 introduces the #[\NoDiscard] attribute.
This attribute allows developers to mark methods whose return values must be used. If the return value is ignored, PHP emits a warning, catching potential silent failures at development time.
Why use this pattern?
- Safety: Prevents "fire and forget" bugs where errors are missed.
- Clarity: Signals that the return value contains critical information (like success/failure status).
- Robustness: Enforces a "Result Pattern" where every outcome must be handled.
๐ฆ Installation
composer require alizharb/php85-safe-api-client
โ ๏ธ Requirement: This library requires PHP 8.5 or higher.
๐ง Usage
The Safe Way (Correct)
Assign the result and handle it.
use SafeApiClient\Client; use SafeApiClient\Success; use SafeApiClient\Failure; $client = new Client(); // โ Correct: The result is assigned and used $result = $client->get('https://api.example.com/data'); if ($result instanceof Success) { echo "Data: " . $result->value->body; } elseif ($result instanceof Failure) { echo "Error: " . $result->error->getMessage(); }
The Unsafe Way (Triggers Warning)
If you ignore the return value, PHP 8.5 will warn you.
// โ ๏ธ Warning: Unused return value of method SafeApiClient\Client::get marked with #[\NoDiscard] $client->get('https://api.example.com/data');
๐ API Reference
Client
get(string $url): Result- marked with#[\NoDiscard]post(string $url, array $data): Result- marked with#[\NoDiscard]
Result
isSuccess(): boolisFailure(): bool
๐งช Testing
Run the test suite with PHPUnit:
composer test
๐ค Contributing
Contributions are welcome! Please see CONTRIBUTING.md for details.
๐ License
This project is licensed under the MIT License. See the LICENSE file for details.
Made with โค๏ธ by Ali Harb