https://github.com/krakphp/http
Http Utilities for PSR-7 Frameworks
https://github.com/krakphp/http
Last synced: 10 months ago
JSON representation
Http Utilities for PSR-7 Frameworks
- Host: GitHub
- URL: https://github.com/krakphp/http
- Owner: krakphp
- Created: 2016-11-23T12:25:07.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-05-14T06:37:17.000Z (about 9 years ago)
- Last Synced: 2025-03-01T10:36:54.914Z (over 1 year ago)
- Language: PHP
- Homepage:
- Size: 94.7 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
# Http
The Krak Http package is a set of utilities for building Http applications. It comes with an implementation agnostic routing system, PSR-7 Response Factories, PSR-7 Server implementation, and a handful of useful middleware for Http applications.
## Installation
Install via composer at `krak/http`
## Usage
### Response Factories
```php
createResponse(200, [], [1,2,3]);
```
### Routes
```php
get('/', function() {})->with('attribute', 'value');
$routes->group('/foo', function($foo) {
$sub->get('', 'handler');
$sub->group('/bar', function($bar) {
$bar->get('/baz', 'handler');
});
});
$routes->with('attribute1', 'value');
```
### Compiling Routes
Once you've created a set of routes, you can then compile them with a route compiler. These will traverse the hierarchy of routes and flatten them into an iterator with normalized paths.
```php
compileRoutes($routes, '/');
```
### Dispatch
To dispatch a set of routes, you need to create dispatcher factory, which will create a dispatcher from a set of routes, then you can dispatch a PSR-7 request.
```php
createDispatcher($routes);
$res = $dispatch->dispatch($req);
// $res->status_code
// $res->matched_route->route
// $res->matched_route->params
// $res->allowed_methods /* if status code is a 405 response */
```
### Server
The server is responsible for creating a request, and emitting a response. It's a simple interface:
```php
serve(function($req) {
return new Zend\Diactoros\Response();
});
```
### Middleware
Here are several useful middleware to use within your own applications. Each middleware takes two arguments: A PSR-7 Server Request, and an HttpLink. If you want more documentation on how the Link's work, checkout the Krak\\Mw library.
```php
withAttribute('a', '1'))->withStatusCode(404);
}
return $next->response(404, ['X-Header' => 'value'], 'Some body'); // can also use a php or psr-7 stream.
};
}
```
#### injectRequestAttribute($name, $value)
This will automatically inject an attribute with a name and the given value.
#### wrap($psr7_middleware)
This will wrap PSR-7 style middleware that use the request and response in the middleware parameters.
```php