Skip to content

Commit 0e0f2aa

Browse files
committed
Merge branch 'develop' of github.com:MaplePHP/Http into develop
2 parents 09c822b + 70fa5e7 commit 0e0f2aa

File tree

4 files changed

+285
-87
lines changed

4 files changed

+285
-87
lines changed

README.md

Lines changed: 223 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,125 +1,253 @@
1+
2+
13
# MaplePHP - A Full-Featured PSR-7 Compliant HTTP Library
2-
MaplePHP/Http is a PHP library that brings simplicity and adherence to the PSR-7 standard into handling HTTP messages, requests, and responses within your web projects. It's thoughtfully designed to make the integration of crucial elements like Stream, Client, Cookies, UploadedFile, and Headers straightforward and efficient.
34

4-
By aligning closely with PSR-7, MaplePHP/Http facilitates better interoperability between web components, allowing for more effective communication within applications. Whether you're working with client-side cookies, managing headers in a request, or handling file uploads through UploadedFile, this library has got you covered, making these tasks more manageable and less time-consuming.
5+
**MaplePHP/Http** is a powerful and easy-to-use PHP library that fully supports the PSR-7 HTTP message interfaces. It simplifies handling HTTP requests, responses, streams, URIs, and uploaded files, making it an excellent choice for developers who want to build robust and interoperable web applications.
6+
7+
With MaplePHP, you can effortlessly work with HTTP messages while adhering to modern PHP standards, ensuring compatibility with other PSR-7 compliant libraries.
58

6-
MaplePHP/Http aims to support your web development by offering a reliable foundation for working with HTTP messaging, streamlining the process of dealing with requests and responses. It's a practical choice for developers looking to enhance their applications with PSR-7 compliant HTTP handling in a user-friendly way.
9+
## Why Choose MaplePHP?
710

11+
- **Full PSR-7 Compliance**: Seamlessly integrates with other PSR-7 compatible libraries and frameworks.
12+
- **User-Friendly API**: Designed with developers in mind for an intuitive and straightforward experience.
13+
- **Comprehensive Functionality**: Handles all aspects of HTTP messaging, including requests, responses, streams, URIs, and file uploads.
14+
- **Flexible and Extensible**: Easily adapts to projects of any size and complexity.
815

916
## Installation
1017

11-
```
18+
Install MaplePHP via Composer:
19+
20+
```bash
1221
composer require maplephp/http
1322
```
1423

15-
## Initialize
16-
The **examples** below is utilizing the "namespace" below just to more easily demonstrate the guide.
1724

18-
```php
19-
use MaplePHP\Http;
20-
```
2125

26+
### Handling HTTP Requests
2227

23-
## Request
28+
#### Creating a Server Request
29+
30+
To create a server request, use the `ServerRequest` class:
2431

2532
```php
26-
$request = new Http\ServerRequest(UriInterface $uri, EnvironmentInterface $env);
27-
```
28-
#### Get request method
29-
```php
30-
echo $request->getMethod(); // GET, POST, PUT, DELETE
33+
use MaplePHP\Http\ServerRequest;
34+
use MaplePHP\Http\Uri;
35+
use MaplePHP\Http\Environment;
36+
37+
// Create an environment instance (wraps $_SERVER)
38+
$env = new Environment();
39+
40+
// Create a URI instance from the environment
41+
$uri = new Uri($env->getUriParts());
42+
43+
// Create the server request
44+
$request = new ServerRequest($uri, $env);
3145
```
32-
#### Get Uri instance
46+
47+
#### Accessing Request Data
48+
49+
You can easily access various parts of the request:
50+
3351
```php
34-
$uri = $request->getUri(); // UriInterface
35-
echo $uri->getScheme(); // https
36-
echo $uri->getAuthority(); // [userInfo@]host[:port]
37-
echo $uri->getUserInfo(); // username:password
38-
echo $uri->getHost(); // example.com, staging.example.com, 127.0.0.1, localhost
39-
echo $uri->getPort(); // 443
40-
echo $uri->getPath(); // /about-us/workers
41-
echo $uri->getQuery(); // page-id=12&filter=2
42-
echo $uri->getFragment(); // anchor-12 (The anchor hash without "#")
43-
echo $uri->getUri(); // Get the full URI
52+
// Get the HTTP method
53+
$method = $request->getMethod(); // e.g., GET, POST
54+
55+
// Get request headers
56+
$headers = $request->getHeaders();
57+
58+
// Get a specific header
59+
$userAgent = $request->getHeaderLine('User-Agent');
60+
61+
// Get query parameters
62+
$queryParams = $request->getQueryParams();
63+
64+
// Get parsed body (for POST requests)
65+
$parsedBody = $request->getParsedBody();
66+
67+
// Get uploaded files
68+
$uploadedFiles = $request->getUploadedFiles();
69+
70+
// Get server attributes
71+
$attributes = $request->getAttributes();
4472
```
45-
## Response
46-
Only the **(StreamInterface) Body** attribute is required and the rest will auto propagate if you leave them be.
73+
74+
#### Modifying the Request
75+
76+
Requests are immutable; methods that modify the request return a new instance:
77+
4778
```php
48-
$response = new Http\Response(
49-
StreamInterface $body,
50-
?HeadersInterface $headers = null,
51-
int $status = 200,
52-
?string $phrase = null,
53-
?string $version = null
54-
);
79+
// Add a new header
80+
$newRequest = $request->withHeader('X-Custom-Header', 'MyValue');
81+
82+
// Change the request method
83+
$newRequest = $request->withMethod('POST');
84+
85+
// Add an attribute
86+
$newRequest = $request->withAttribute('user_id', 123);
5587
```
56-
#### Get Status code
88+
89+
### Managing HTTP Responses
90+
91+
#### Creating a Response
92+
93+
Create a response using the `Response` class:
94+
5795
```php
58-
echo $response->getStatusCode(); // 200
96+
use MaplePHP\Http\Response;
97+
use MaplePHP\Http\Stream;
98+
99+
// Create a stream for the response body
100+
$body = new Stream('php://temp', 'rw');
101+
102+
// Write content to the body
103+
$body->write('Hello, world!');
104+
$body->rewind();
105+
106+
// Create the response with the body
107+
$response = new Response($body);
59108
```
60-
#### Get Status code
109+
110+
#### Setting Status Codes and Headers
111+
112+
You can set the HTTP status code and headers:
113+
61114
```php
62-
$newInst = $response->withStatus(404);
63-
echo $newInst->getStatusCode(); // 404
64-
echo $newInst->getReasonPhrase(); // Not Found
115+
// Set the status code to 200 OK
116+
$response = $response->withStatus(200);
117+
118+
// Add headers
119+
$response = $response->withHeader('Content-Type', 'text/plain');
120+
121+
// Add multiple headers
122+
$response = $response->withAddedHeader('X-Powered-By', 'MaplePHP');
65123
```
66-
## Message
67-
Both Request and Response library will inherit methods under Message but with different information.
124+
125+
#### Sending the Response
126+
127+
To send the response to the client:
128+
68129
```php
69-
echo $response->getProtocolVersion(); // 1.1
70-
echo $response->getHeaders(); // Array with all headers
71-
echo $response->hasHeader("Content-Length"); // True
72-
echo $response->getHeader("Content-Length"); // 1299
73-
echo $response->getBody(); // StreamInterface
130+
// Output headers
131+
foreach ($response->getHeaders() as $name => $values) {
132+
foreach ($values as $value) {
133+
header(sprintf('%s: %s', $name, $value), false);
134+
}
135+
}
136+
137+
// Output status line
138+
header(sprintf(
139+
'HTTP/%s %s %s',
140+
$response->getProtocolVersion(),
141+
$response->getStatusCode(),
142+
$response->getReasonPhrase()
143+
));
144+
145+
// Output body
146+
echo $response->getBody();
74147
```
75148

76-
## A standard example usage
149+
### Working with Streams
150+
151+
Streams are used for the message body in requests and responses.
152+
153+
#### Creating a Stream
154+
Reading and Writing with stream
155+
77156
```php
78-
$stream = new Http\Stream(Http\Stream::TEMP);
79-
$response = new Http\Response($stream);
80-
$env = new Http\Environment();
81-
$request = new Http\ServerRequest(new Http\Uri($env->getUriParts()), $env);
157+
use MaplePHP\Http\Stream;
158+
159+
// Create a stream from a file
160+
//$fileStream = new Stream('/path/to/file.txt', 'r');
161+
162+
// Create a stream from a string
163+
$memoryStream = new Stream(Stream::MEMORY);
164+
//$memoryStream = new Stream('php://memory', 'r+'); // Same as above
165+
$memoryStream->write('Stream content');
166+
167+
// Write to the stream
168+
$memoryStream->write(' More content');
169+
170+
// Read from the stream
171+
$memoryStream->rewind();
172+
echo $memoryStream->getContents();
173+
// Result: 'Stream content More content'
82174
```
83175

84-
## Stream
85-
None of the construct attributes are required and will auto propagate if you leave them be.
176+
177+
#### Using Streams in Requests and Responses
178+
86179
```php
87-
$stream = new Http\Stream(
88-
(mixed) Stream
89-
(string) permission
90-
);
180+
// Set stream as the body of a response
181+
$response = $response->withBody($memoryStream);
91182
```
92-
### Basic stream examples
93183

94-
#### Write to stream
184+
### Manipulating URIs
185+
186+
URIs are used to represent resource identifiers.
187+
188+
#### Creating and Modifying URIs
189+
95190
```php
96-
$stream = new Http\Stream(Http\Stream::TEMP);
97-
if ($stream->isSeekable()) {
98-
$stream->write("Hello world");
99-
//echo $stream; // will print Hello world
100-
// Or
101-
$stream->rewind();
102-
echo $stream->getContents(); // Hello world
103-
// Or Same as above
104-
//echo $stream->read($stream->getSize());
105-
}
191+
// Create a URI instance
192+
$uri = new Uri('http://example.com:8000/path?query=value#fragment');
193+
194+
// Modify the URI
195+
$uri = $uri->withScheme('https')
196+
->withUserInfo('guest', 'password123')
197+
->withHost('example.org')
198+
->withPort(8080)
199+
->withPath('/new-path')
200+
->withQuery('query=newvalue')
201+
->withFragment('section1');
202+
203+
// Convert URI to string
204+
echo $uri; // Outputs the full URI
205+
//Result: https://guest:[email protected]:8080/new-path?query=newvalue#section1
106206
```
107207

108-
#### Get file content with stream
208+
#### Accessing URI Components
209+
109210
```php
110-
$stream = new Http\Stream("/var/www/html/YourApp/dir/dir/data.json");
111-
echo $stream->getContents();
211+
echo $uri->getScheme(); // 'http'
212+
echo $uri->getUserInfo(); // 'guest:password123'
213+
echo $uri->getHost(); // 'example.org'
214+
echo $uri->getPath(); // '/new-path'
215+
echo $uri->getQuery(); // 'key=newvalue'
216+
echo $uri->getFragment(); // 'section1'
217+
echo $uri->getAuthority(); // 'guest:[email protected]:8080'
112218
```
113219

114-
#### Upload a stream to the server
220+
### Handling Uploaded Files
221+
222+
Manage file uploads with ease using the `UploadedFile` class.
223+
224+
#### Accessing Uploaded Files
225+
115226
```php
116-
$upload = new Http\UploadedFile($stream);
117-
$upload->moveTo("/var/www/html/upload/log.txt"); // Place Hello world in txt file
227+
// Get uploaded files from the request
228+
$uploadedFiles = $request->getUploadedFiles();
229+
230+
// Access a specific uploaded file
231+
$uploadedFile = $uploadedFiles['file_upload'];
232+
233+
// Get file details
234+
$clientFilename = $uploadedFile->getClientFilename();
235+
$clientMediaType = $uploadedFile->getClientMediaType();
236+
237+
// Move the uploaded file to a new location
238+
$uploadedFile->moveTo('/path/to/uploads/' . $clientFilename);
118239
```
119240

120-
### Create a request
121-
The client will be using curl, so it's essential to ensure that it is enabled in case it has been disabled for any reason.
241+
### Using the HTTP Client
242+
243+
Send HTTP requests using the built-in HTTP client.
244+
245+
#### Sending a Request
246+
122247
```php
248+
use MaplePHP\Http\Client;
249+
use MaplePHP\Http\Request;
250+
123251
// Init request client
124252
$client = new Http\Client([CURLOPT_HTTPAUTH => CURLAUTH_DIGEST]); // Pass on Curl options
125253

@@ -133,7 +261,20 @@ $request = new Http\Request(
133261

134262
// Pass request data to client and POST
135263
$response = $client->sendRequest($request);
136-
137-
// Get Stream data
138-
var_dump($response->getBody()->getContents());
264+
if ($response->getStatusCode() === 200) {
265+
// Parse the response body
266+
$data = json_decode($response->getBody()->getContents(), true);
267+
// Use the data
268+
echo 'User Name: ' . $data['name'];
269+
} else {
270+
echo 'Error: ' . $response->getReasonPhrase();
271+
}
139272
```
273+
274+
## Conclusion
275+
276+
**MaplePHP/Http** is a comprehensive library that makes working with HTTP in PHP a breeze. Its full PSR-7 compliance ensures that your applications are built on solid, modern standards, promoting interoperability and maintainability.
277+
278+
Whether you're handling incoming requests, crafting responses, manipulating URIs, working with streams, or managing file uploads, MaplePHP provides a clean and intuitive API that simplifies your development process.
279+
280+
Get started today and enhance your PHP applications with MaplePHP!

0 commit comments

Comments
 (0)