Response
is a lightweight PHP library designed to streamline API response handling. It follows a singleton-based pattern to store and retrieve results, errors, and user input efficiently. The package is PSR-4 compliant and fully compatible with PHP 7.2+ and PHP 8.2.
- ✅ Singleton pattern to prevent redundant object creation.
- ✅ Structured response handling for JSON and array outputs.
- ✅ Collect API results & errors dynamically.
- ✅ Retrieve user input from
$_GET
,$_POST
, and JSON payloads. - ✅ Flexible data retrieval (JSON, array, collection format).
- ✅ Works with Laravel, Symfony, CodeIgniter, WordPress, and Core PHP.
You can install this package using Composer:
composer require uxmansarwar/response
Alternatively, clone this repository and include it in your project:
git clone https://github.com/uxmansarwar/Response.git
Then, include the autoloader:
require 'vendor/autoload.php';
use UxmanSarwar\Response;
Response::init();
Response::result("User created successfully");
Response::result(["id" => 1, "name" => "John Doe"]);
Response::error("Invalid API request");
Response::error("Failed to connect to the database");
echo Response::json();
Example Output:
{
"result": [
"User created successfully",
{ "id": 1, "name": "John Doe" }
],
"error": [
"Invalid API request",
"Failed to connect to the database"
]
}
$response_array = Response::collection();
print_r($response_array);
Response::key("user")->result(["id" => 2, "name" => "Jane Doe"]);
echo Response::json();
Response::input(true);
echo Response::json();
If a request is made with:
GET /api.php?id=10&name=Alice
The output will include:
"input": {
"id": "10",
"name": "Alice"
}
You can define custom keys for results and errors:
Response::key("dns");
Response::init();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
Response::error("Only POST requests are allowed");
} else {
$data = Response::$_INPUT;
if (!isset($data['username']) || empty($data['username'])) {
Response::error("Username is required");
} else {
Response::result("User registered successfully");
}
}
echo Response::json();
To install and run tests:
composer install
vendor/bin/phpstan analyse src --level=max
vendor/bin/pest