Skip to content

Commit 372ac0c

Browse files
authored
Merge pull request #7 from uxmansarwar/uxman_dev
feat: improve core functionality and enhance README with composer ins…
2 parents a73215f + f7cd63e commit 372ac0c

File tree

8 files changed

+303
-130
lines changed

8 files changed

+303
-130
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,4 @@
2424
/app/Config/database.php
2525
/vendors/*
2626

27+
/composer.lock

CHANGELOG.md

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,28 @@
11
# Changelog
22

3-
## [released]
4-
3+
## [3.0.0] - 2025-03-11
54
### Added
6-
- Initial release of `uxmansarwar/response`.
7-
- Added result and error storage.
8-
- JSON, array, response support.
9-
- User input handling.
5+
- **PHPStan Compliant Developer Comments**: Added detailed PHPStan-compliant comments to improve code readability and maintainability.
6+
- **`collection()` Method**: Introduced a new method to centralize response data collection, reducing redundancy in `json()` and `array()`.
7+
- **Static Response Key Names**: Defined `$result_key_text`, `$error_key_text`, and `$input_key_text` as static class properties for better maintainability.
108

11-
## [1.0.0] - 2025-02-20
9+
### Changed
10+
- **Singleton Handling**: Improved `singleton()` method for better reusability instead of initializing in multiple places.
11+
- **Constructor Reset Behavior**: Adjusted constructor logic to ensure that each instantiation resets response states correctly.
12+
- **JSON Parsing Validation**: Enhanced JSON request body parsing by verifying `json_last_error()`.
13+
- **Better Result & Error Storage**: Updated result and error storage to always ensure correct structuring when using keys.
14+
15+
### Fixed
16+
- **Incorrect Singleton Reinitialization**: Ensured `singleton()` and `init()` methods correctly maintain a single instance.
17+
- **Input Handling Edge Cases**: Addressed cases where JSON input merging could fail under certain request formats.
18+
- **Return Consistency**: Standardized method return values to always return `self` where applicable for method chaining.
19+
20+
---
21+
22+
## [2.0.1] - Previous Version
23+
### Initial Features
24+
- Implemented Singleton pattern.
25+
- Added methods for storing results (`result()`) and errors (`error()`).
26+
- Supported response output in both JSON (`json()`) and array (`array()`) formats.
27+
- Allowed toggling of user input inclusion in responses via `input()` method.
1228

13-
### Added
14-
- First stable release.

README.md

Lines changed: 86 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,117 +1,125 @@
1-
# Response
1+
# Response - PHP API Response Handler
22

3-
Response is a PHP class designed to manage API responses efficiently. It provides a singleton-based approach to storing and retrieving results, errors, and user input data in multiple formats (JSON, array). This class ensures proper handling of API responses while maintaining PHP 7+ compatibility.
3+
[![Packagist](https://img.shields.io/packagist/v/uxmansarwar/response)](https://packagist.org/packages/uxmansarwar/response)
4+
[![PHP Version](https://img.shields.io/badge/php-%3E%3D7.2-blue)](https://www.php.net/)
5+
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
46

5-
## Features
6-
- Singleton pattern ensures a single instance.
7-
- Store results and errors dynamically.
8-
- Capture user input from `$_GET`, `$_POST`, and JSON payloads.
9-
- Retrieve stored data in JSON, array, format.
10-
- Support for enabling/disabling user input inclusion in responses.
11-
- Works on PHP 7 and above.
7+
## Overview
8+
9+
`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**.
10+
11+
### **Key Features**
12+
-**Singleton pattern** to prevent redundant object creation.
13+
-**Structured response handling** for JSON and array outputs.
14+
-**Collect API results & errors dynamically**.
15+
-**Retrieve user input** from `$_GET`, `$_POST`, and JSON payloads.
16+
-**Flexible data retrieval** (JSON, array, collection format).
17+
-**Works with Laravel, Symfony, CodeIgniter, WordPress, and Core PHP**.
18+
19+
---
1220

1321
## Installation
14-
Clone the repository into your project directory:
1522

23+
### **Install via Composer**
24+
You can install this package using Composer:
1625
```sh
17-
$ git clone https://github.com/yourusername/Response.git
26+
composer require uxmansarwar/response
1827
```
1928

20-
Include the `Response.php` file in your project:
21-
29+
### **Manual Installation**
30+
Alternatively, clone this repository and include it in your project:
31+
```sh
32+
git clone https://github.com/uxmansarwar/Response.git
33+
```
34+
Then, include the autoloader:
2235
```php
23-
require_once 'Response.php';
36+
require 'vendor/autoload.php';
2437
```
2538

26-
## Usage
27-
### Initializing the Response
28-
Since `Response` follows the singleton pattern, you do not instantiate it directly. Instead, use the `init()` method:
39+
---
40+
41+
## **Usage Examples**
2942

43+
### **1. Initializing the Response Handler**
3044
```php
45+
use UxmanSarwar\Response;
46+
3147
Response::init();
3248
```
3349

34-
### Storing Results
35-
You can store multiple results dynamically using the `result()` method:
36-
50+
### **2. Storing Results**
3751
```php
38-
Response::result("Operation successful");
52+
Response::result("User created successfully");
3953
Response::result(["id" => 1, "name" => "John Doe"]);
4054
```
4155

42-
### Storing Errors
43-
Similarly, errors can be stored using the `error()` method:
44-
56+
### **3. Handling Errors**
4557
```php
46-
Response::error("Invalid request");
47-
Response::error("Database connection failed");
58+
Response::error("Invalid API request");
59+
Response::error("Failed to connect to the database");
4860
```
4961

50-
### Retrieving Data
51-
You can retrieve the stored results and errors in different formats:
52-
53-
#### JSON Format
62+
### **4. Retrieving Response Data**
63+
#### JSON Output:
5464
```php
5565
echo Response::json();
5666
```
57-
**Output:**
67+
**Example Output:**
5868
```json
5969
{
6070
"result": [
61-
"Operation successful",
71+
"User created successfully",
6272
{ "id": 1, "name": "John Doe" }
6373
],
6474
"error": [
65-
"Invalid request",
66-
"Database connection failed"
75+
"Invalid API request",
76+
"Failed to connect to the database"
6777
]
6878
}
6979
```
7080

71-
#### Array Format
81+
#### Array Output:
7282
```php
73-
$response_array = Response::array();
83+
$response_array = Response::collection();
7484
print_r($response_array);
7585
```
76-
**Output:**
86+
87+
---
88+
89+
## **Advanced Features**
90+
91+
### **5. Grouping Responses with a Key**
7792
```php
78-
Array (
79-
[result] => Array (
80-
[0] => Operation successful
81-
[1] => Array ([id] => 1, [name] => John Doe)
82-
)
83-
[error] => Array (
84-
[0] => Invalid request
85-
[1] => Database connection failed
86-
)
87-
)
93+
Response::key("user")->result(["id" => 2, "name" => "Jane Doe"]);
94+
echo Response::json();
8895
```
8996

90-
### Handling User Input
91-
User input (from `$_GET`, `$_POST`, or JSON requests) is captured automatically. You can include it in the response using:
92-
97+
### **6. Include User Input in Response**
9398
```php
9499
Response::input(true);
95100
echo Response::json();
96101
```
97102
If a request is made with:
98103
```sh
99-
GET /api.php?id=5&name=John
104+
GET /api.php?id=10&name=Alice
100105
```
101-
The output will be:
106+
The output will include:
102107
```json
103-
{
104-
"result": [],
105-
"error": [],
106-
"input": {
107-
"id": "5",
108-
"name": "John"
109-
}
108+
"input": {
109+
"id": "10",
110+
"name": "Alice"
110111
}
111112
```
112113

113-
### Example Use Case
114-
#### API Response Handling
114+
### **7. Custom Error & Result Keys**
115+
You can define custom keys for results and errors:
116+
```php
117+
Response::key("dns");
118+
```
119+
120+
---
121+
122+
## **Use Case Example: API Response Handling**
115123
```php
116124
Response::init();
117125

@@ -129,9 +137,22 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
129137
echo Response::json();
130138
```
131139

132-
### Contributing
133-
Feel free to fork this repository, make enhancements, and submit pull requests. Suggestions and issues are welcome!
140+
---
141+
142+
## **Why Use This Package?**
143+
### **For Laravel & Symfony Developers**: Use it as a service-based response handler.
144+
### **For WordPress Developers**: Improve structured AJAX responses.
145+
### **For REST API Development**: Optimize API response handling with minimal effort.
146+
### **For Microservices**: Centralize error handling and response formatting.
147+
148+
---
149+
150+
## **Testing the Package**
151+
To install and run tests:
152+
```sh
153+
composer install
154+
vendor/bin/phpstan analyse src --level=max
155+
vendor/bin/pest
156+
```
134157

135-
### License
136-
This project is licensed under the MIT License.
137158

composer.json

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
{
22
"name": "uxmansarwar/response",
3-
"description": "",
3+
"description": "A lightweight PHP response handler for structured API responses.",
44
"keywords": [
5-
"response handler - collector"
5+
"php",
6+
"response",
7+
"api",
8+
"response handler",
9+
"error handling",
10+
"json response",
11+
"response collector"
612
],
713
"type": "library",
8-
"license": "proprietary",
14+
"license": "MIT",
915
"authors": [
1016
{
1117
"name": "Uxman Sarwar",
@@ -15,6 +21,7 @@
1521
],
1622
"config": {
1723
"sort-packages": true,
24+
"prefer-stable": true,
1825
"allow-plugins": {
1926
"pestphp/pest-plugin": true
2027
}
@@ -30,7 +37,9 @@
3037
"require-dev": {
3138
"friendsofphp/php-cs-fixer": "^3.35",
3239
"pestphp/pest": "^2.34",
33-
"phpstan/phpstan": "^1.10"
40+
"phpstan/phpstan": "^1.10",
41+
"mockery/mockery": "^1.6",
42+
"phpunit/phpunit": "^10.4"
3443
},
3544
"minimum-stability": "stable"
36-
}
45+
}

examples/example.php

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,36 @@
44

55
use UxmanSarwar\Response as res;
66

7-
res::init()->input(true);
8-
res::key('mysql')->result(['sql' => 'this is value related to upcoming sorting thing']);
9-
res::result('this is value 2');
107

11-
res::key('mysql-2')->result(['sql' => 'this is value related to upcoming sorting thing']);
12-
res::result('this is value 2');
13-
res::result('this is value 2');
14-
res::result('this is value 2');
8+
// ------------------------------------------------------v3.0.0
159

16-
res::key();
1710

18-
res::error('MySql got error');
1911

20-
echo res::json();
12+
13+
14+
15+
16+
// ------------------------------------------------------v3.0.0
17+
18+
19+
echo res::init();
20+
21+
22+
// ------------------------------------------------------
23+
// res::init()->input(true);
24+
// res::key('mysql')->result(['sql' => 'this is value related to upcoming sorting thing']);
25+
// res::result('this is value 2');
26+
27+
// res::key('mysql-2')->result(['sql' => 'this is value related to upcoming sorting thing']);
28+
// res::result('this is value 2');
29+
// res::result('this is value 2');
30+
// res::result('this is value 2');
31+
32+
// res::key();
33+
34+
// res::error('MySql got error');
35+
36+
// echo res::json();
2137

2238

2339

phpstan.neon

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
parameters:
2+
level: max
3+
paths:
4+
- tests
5+
bootstrapFiles: []

0 commit comments

Comments
 (0)