PHP code example of free-elephants / rest-daemon

1. Go to this page and download the library: Download free-elephants/rest-daemon library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

free-elephants / rest-daemon example snippets



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);


$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);


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

# 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