PHP code example of woohoolabs / harmony

1. Go to this page and download the library: Download woohoolabs/harmony 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/ */

    

woohoolabs / harmony example snippets


namespace App\Controllers;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

class UserController
{
    public function getUsers(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $users = ["Steve", "Arnie", "Jason", "Bud"];
        $response->getBody()->write(json_encode($users));

        return $response;
    }

    public function updateUser(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $userId = $request->getAttribute("id");
        $userData = $request->getParsedBody();

        // Updating user...

        return $response;
    }
}

use App\Controllers\UserController;

$router = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    // An anonymous function endpoint
    $r->addRoute("GET", "/me", function (ServerRequestInterface $request, ResponseInterface $response) {
            // ...
    });

    // Class method endpoints
    $r->addRoute("GET", "/users", [UserController::class, "getUsers"]);
    $r->addRoute("POST", "/users/{id}", [UserController::class, "updateUser"]);
});

use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequestFactory;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use WoohooLabs\Harmony\Harmony;
use WoohooLabs\Harmony\Middleware\DispatcherMiddleware;
use WoohooLabs\Harmony\Middleware\FastRouteMiddleware;
use WoohooLabs\Harmony\Middleware\LaminasEmitterMiddleware;

$harmony = new Harmony(ServerRequestFactory::fromGlobals(), new Response());
$harmony
    ->addMiddleware(new LaminasEmitterMiddleware(new SapiEmitter()))
    ->addMiddleware(new FastRouteMiddleware($router))
    ->addMiddleware(new DispatcherMiddleware())
    ->run();

$router->addRoute("GET", "/users/me", [\App\Controllers\UserController::class, "getMe"]);

$router->addRoute("GET", "/users/me", \App\Controllers\GetMe::class);

$container = new MyContainer();
$harmony->addMiddleware(new DispatcherMiddleware($container));

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;

class LoggerMiddleware implements MiddlewareInterface
{
    private LoggerInterface $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Perform logging before handling the request
        $this->logger->info("Request needs to be handled");

        // Invoking the remaining middleware
        $response = $handler->handle($request);

        // Perform logging after the request has been handled
        $this->logger->info("Request was successfully handled");

        // Return the response
        return $response;
    }
}

$harmony->addMiddleware(new LoggerMiddleware(new Logger()));

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthenticationMiddleware implements MiddlewareInterface
{
    protected string $apiKey;
    protected ResponseInterface $errorResponsePrototype;

    public function __construct(string $apiKey, ResponseInterface $errorResponsePrototype)
    {
        $this->apiKey = $apiKey;
        $this->errorResponsePrototype = $errorResponsePrototype;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Return Error 401 "Unauthorized" if the provided API key doesn't match the expected one
        if ($request->getHeader("x-api-key") !== [$this->apiKey]) {
            return $this->errorResponsePrototype->withStatus(401);
        }

        // Invoke the remaining middleware if authentication was successful
        return $handler->handle($request);
    }
}

$harmony->addMiddleware(new AuthenticationMiddleware("123"), new Response());

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthenticationMiddleware implements MiddlewareInterface
{
    protected string $securedPath;
    protected MyAuthenticatorInterface $authenticator;
    protected ResponseInterface $errorResponsePrototype;

    public function __construct(string $securedPath, MyAuthenticatorInterface $authenticator, ResponseInterface $errorResponsePrototype)
    {
        $this->securedPath = $securedPath;
        $this->authenticator = $authenticator;
        $this->errorResponsePrototype = $errorResponsePrototype;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Invoke the remaining middleware and cancel authentication if the current URL is for a public endpoint
        if (substr($request->getUri()->getPath(), 0, strlen($this->securedPath)) !== $this->securedPath) {
            return $handler->handle($request);
        }

        // Return Error 401 "Unauthorized" if authentication fails
        if ($this->authenticator->authenticate($request) === false) {
            return $this->errorResponsePrototype->withStatusCode(401);
        }

        // Invoke the remaining middleware otherwise
        return $handler->handle($request);
    }
}

$harmony->addMiddleware(new AuthenticationMiddleware("/users", new ApiKeyAuthenticator("123"), new Response()));

$harmony->addCondition(
    new PathPrefixCondition(["/users"]),
    static function (Harmony $harmony) {
        $harmony->addMiddleware(new AuthenticationMiddleware(new ApiKeyAuthenticator("123")));
    }
);