PHP code example of larananas / lumen-json-rpc

1. Go to this page and download the library: Download larananas/lumen-json-rpc 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/ */

    

larananas / lumen-json-rpc example snippets




declare(strict_types=1);

;
use Lumen\JsonRpc\Server\JsonRpcServer;

$config = new Config([
    'handlers' => [
        'paths' => [__DIR__ . '/../handlers'],
        'namespace' => 'App\\Handlers\\',
    ],
]);

$server = new JsonRpcServer($config);
$server->run();



declare(strict_types=1);

namespace App\Handlers;

use Lumen\JsonRpc\Support\RequestContext;

final class User
{
    public function get(RequestContext $context, int $id): array
    {
        return [
            'id' => $id,
            'name' => 'Example User',
            'requested_by' => $context->authUserId,
        ];
    }
}

'auth' => [
    'enabled' => true,
    'driver' => 'jwt', // jwt | api_key | basic
    'protected_methods' => ['user.', 'order.'],
],



use Lumen\JsonRpc\Support\RequestContext;

$context = new RequestContext(
    correlationId: 'demo-1',
    headers: [],
    clientIp: '127.0.0.1',
    requestBody: '{"jsonrpc":"2.0","method":"system.health","id":1}'
);

$json = $server->handleJson(
    '{"jsonrpc":"2.0","method":"system.health","id":1}',
    $context,
);

echo $json;

$context = $server->authenticateContext($context);

$server->setRequestAuthenticator(new MyRequestAuthenticator());



use Lumen\JsonRpc\Dispatcher\HandlerFactoryInterface;
use Lumen\JsonRpc\Support\RequestContext;

$factory = new class($db) implements HandlerFactoryInterface {
    public function __construct(private DatabaseService $db) {}

    public function create(string $className, RequestContext $context): object
    {
        return new $className($this->db);
    }
};

$server->setHandlerFactory($factory);



use Lumen\JsonRpc\Middleware\MiddlewareInterface;
use Lumen\JsonRpc\Protocol\Request;
use Lumen\JsonRpc\Protocol\Response;
use Lumen\JsonRpc\Support\RequestContext;

$server->addMiddleware(new class implements MiddlewareInterface {
    public function process(Request $request, RequestContext $context, callable $next): ?Response
    {
        error_log("[JSON-RPC] -> {$request->method}");
        $response = $next($request, $context);
        error_log('[JSON-RPC] <- done');
        return $response;
    }
});



use Lumen\JsonRpc\Dispatcher\ProcedureDescriptor;

$registry = $server->getRegistry();

$registry->register('math.add', MathHandler::class, 'add', [
    'description' => 'Add two numbers',
]);

// Or batch-register descriptor objects:
$registry->registerDescriptors([
    new ProcedureDescriptor('math.add', MathHandler::class, 'add', ['description' => 'Add two numbers']),
    new ProcedureDescriptor('math.multiply', MathHandler::class, 'multiply'),
]);



use Lumen\JsonRpc\Validation\RpcSchemaProviderInterface;

final class Product implements RpcSchemaProviderInterface
{
    public static function rpcValidationSchemas(): array
    {
        return [
            'create' => [
                'type' => 'object',
                '

'validation' => [
    'strict' => true,
    'schema' => ['enabled' => true],
],

'auth' => [
    'enabled' => true,
    'driver' => 'jwt',
    'protected_methods' => ['user.', 'order.'],
    'jwt' => [
        'secret' => 'your-secret-key',
        'algorithm' => 'HS256',
        'header' => 'Authorization',
        'prefix' => 'Bearer ',
        'issuer' => '',
        'audience' => '',
        'leeway' => 0,
    ],
],

'auth' => [
    'enabled' => true,
    'driver' => 'api_key',
    'protected_methods' => ['user.'],
    'api_key' => [
        'header' => 'X-API-Key',
        'keys' => [
            'demo-key-123' => [
                'user_id' => 'service-name',
                'roles' => ['service'],
                'claims' => ['source' => 'api_key'],
            ],
        ],
    ],
],

'auth' => [
    'enabled' => true,
    'driver' => 'basic',
    'protected_methods' => ['user.'],
    'basic' => [
        'users' => [
            'admin' => [
                'password_hash' => password_hash('secret', PASSWORD_DEFAULT),
                'user_id' => 'admin',
                'roles' => ['admin'],
            ],
        ],
    ],
],

public function me(RequestContext $context): array
{
    return [
        'id' => $context->authUserId,
        'roles' => $context->authRoles,
        'email' => $context->getClaim('email'),
    ];
}

'rate_limit' => [
    'enabled' => true,
    'max_requests' => 100,
    'window_seconds' => 60,
    'strategy' => 'ip',
    'fail_open' => false,
],

$server->setRateLimiter(new MyRedisRateLimiter());

'batch' => [
    'max_items' => 50,
],

'response_fingerprint' => ['enabled' => true, 'algorithm' => 'sha256'],

$server->getHooks()->register(
    HookPoint::BEFORE_HANDLER,
    function (array $context) {
        return ['custom_data' => 'value'];
    }
);
bash
php bin/generate-docs.php --config=./config.php --format=markdown --output=docs/api.md
php bin/generate-docs.php --config=./config.php --format=html --output=docs/api.html
php bin/generate-docs.php --config=./config.php --format=json --output=docs/api.json
php bin/generate-docs.php --config=./config.php --format=openrpc --output=docs/openrpc.json
bash
php bin/build-docs-site.php
bash
DOCS_CNAME=your-domain.example.com php bin/build-docs-site.php