Coder Social home page Coder Social logo

rest-daemon's Introduction

Rest-Daemon

Build Status codecov Installs Releases

Nota Bene: This project uses semver and changelog. But it's not a stable major version. Any minor update (f.e. 0.5.* -> 0.6.*) can break backward compatibility!

Simple PHP7 framework for fast building REST services based on middleware, PSR-7 and react.

Runned instance can be found by link, also see example repo.

Features:

  • Middleware oriented request/response handling
  • Priority PSR's support: PSR-2, -3, -4, -7, -11, -15 and other.
  • Built-in Middleware to support usual REST features, like HTTP based semantics, content types, request parsing, headers.
  • Choose one of two available http-daemon drivers: Ratchet ReactPHP or Aerys.
  • Swagger Integration

Installation

$ composer require free-elephants/rest-daemon

Usage

See example in example/rest-server.php and documentation.

Create and Run Server:

# your rest-server.php script
$server = new RestServer('127.0.0.1', 8080, '0.0.0.0', ['*']); // <- it's default arguments values
$server->run();

# can be runned as
$ php ./rest-server.php 

Add Your RESTful API Endpoints

Any endpoint method handler can be Middleware-like callable implementation: function or class with __invoke() method.

<?php
class GetAttributeHandler extends AbstractEndpointMethodHandler
{

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
    {
        $name = $request->getAttribute('name', 'World');
        $response->getBody()->write('{
            "hello": "' . $name . '!"
        }');
        return $next($request, $response);
    }
}

$greetingAttributeEndpoint = new BaseEndpoint('/greeting/{name}', 'Greeting by name in path');
$greetingAttributeEndpoint->setMethodHandler('GET', new GetAttributeHandler());

$server->addEndpoint($greetingAttributeEndpoint);

See how to build server for step by step in one script

RestServerBuilder

You can use php-di (or another PSR-11 container implementation) and routing file configuration with RestServerBuilder for more configuring and coding less.

See example with file based routing and dependencies configuration: rest-server.php

Routing

You can link with every method in route a handler, and optionally organize routes by modules. By default server contain 1 default module for all endpoints. See example: routes.php

Configure Common Application Middleware

By default server instance provide collection with some useful middleware. You can extend or override it:

<?php
$requestCounter = function (
    ServerRequestInterface $request,
    ResponseInterface $response,
    callable $next
) {
    static $requestNumber = 0;
    printf('[%s] request number #%d handled' . PHP_EOL, date(DATE_ISO8601), ++$requestNumber);

    return $next($request, $response);
};
$extendedDefaultMiddlewareCollection = new DefaultEndpointMiddlewareCollection([], [$requestCounter]);
$server->setMiddlewareCollection($extendedDefaultMiddlewareCollection);

Every endpoint's method handler will be wrapped to this collection and called between defined as after and before middleware. Also you can configure default middleware collection with access to every built-in middleware by key: this collection implements ArrayAccess interface.

<?php
$server->getMiddlewareCollection()->getBefore()->offsetUnset(\FreeElephants\RestDaemon\Middleware\MiddlewareRole::NO_CONTENT_STATUS_SETTER);

Customize Endpoint Middleware

... Will be implemented...

Debugging and Logging

... Will be implemented...

rest-daemon's People

Contributors

samizdam avatar vehsamrak avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

rest-daemon's Issues

How to handle HTTP OPTIONS preflight requests (CORS)?

I'm using DefaultBeforeMiddlewareCollection to add CORS header. But with an OPTIONS request the middleware don't get called at all.

Ratchet and Aerys seems not to handle OPTIONS requests by themselves. At least I haven't found a solution.

Providing an options handler for every endpoints seems to be a overkill.

Is there a solution for that?

Fix CORS headers

Send Access-Control-Allow-Headers and Access-Control-Allow-Methods with response when Access-Control-Request-Headers and Access-Control-Request-Method are presents.

CLI Application error on start

$ vendor/bin/rest-deamon 
PHP Fatal error:  Uncaught Error: Class 'Symfony\Component\Console\Application' not found in /home/samizdam/dev/projects/rest-daemon-uptime/vendor/free-elephants/rest-daemon/bin/rest-deamon:24
Stack trace:
#0 {main}
  thrown in /home/samizdam/dev/projects/rest-daemon-uptime/vendor/free-elephants/rest-daemon/bin/rest-deamon on line 24

Version installed via composer: 0.12, null of custom configuration, PHP version: 7.3.

Logging

Inject PSR-3 compatible logger.

Nested query params doesn't pasring corrent when use AERYS_HTTP_DRIVER

Affected version: 0.13.0.

Request example:
curl -g "http://127.0.0.1:9000/api/v0/exchanges?filter[post]=1,2&filter[author]=12"

Actual result:

array(2) {
  'filter[post]' =>
  array(1) {
    [0] =>
    string(3) "1,2"
  }
  'filter[author]' =>
  array(1) {
    [0] =>
    string(2) "12"
  }
}

Expected result:

array(1) {
  'filter' =>
  array(2) {
    'post' =>
    string(3) "1,2"
    'author' =>
    string(2) "12"
  }
}

Ratchet driver work fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.