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

v1.0.0 2025-11-20 23:22 UTC

This package is auto-updated.

Last update: 2025-11-20 23:27:22 UTC


README

PHP Version License Build Status

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(): bool
  • isFailure(): 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