An open API service indexing awesome lists of open source software.

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

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