1. Go to this page and download the library: Download knetesin/json-rpc-server 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/ */
knetesin / json-rpc-server example snippets
#[Rpc\Method('user.update', roles: ['ROLE_USER'])]
final class UpdateUser
{
public function __construct(private readonly UserApi $users) {}
public function __invoke(UpdateUserRequest $req, Context $ctx): UserResponse
{
return UserResponse::fromArray(
$this->users->update($req->id, $req->toArray(), $ctx->user->getId()),
);
}
}
// src/Rpc/Add.php
use Knetesin\JsonRpcServerBundle\Attribute as Rpc;
#[Rpc\Method('math.add', description: 'Add two integers.')]
final class Add
{
public function __invoke(int $a, int $b): array
{
return ['sum' => $a + $b];
}
}
final class UpdateUserRequest
{
public function __construct(
#[Assert\Uuid] public string $id,
#[Assert\Length(min: 2, max: 120)] public string $name,
#[Assert\Email] public ?string $email = null,
public ?Date $birthday = null,
) {}
}
#[Rpc\Method('user.update', roles: ['ROLE_USER'])]
final class UpdateUser
{
public function __invoke(UpdateUserRequest $req, Context $ctx): UserResponse { /* … */ }
}
#[Rpc\Method('export.users')]
#[Rpc\Stream(format: StreamFormat::Ndjson)]
final class ExportUsers
{
public function __invoke(ExportRequest $req): \Generator
{
foreach ($this->repo->iterate($req->filters) as $row) {
yield $row;
}
}
}
final class QuotaExceededException extends RpcException
{
public function __construct(int $used, int $limit) {
parent::__construct(sprintf('Quota exceeded: %d/%d', $used, $limit));
}
public function rpcCode(): int { return -32010; }
public function rpcData(): mixed { return ['retryAfter' => 60]; }
}
throw new QuotaExceededException($used, $limit);
public function __invoke(MyRequest $req, Context $ctx): MyResponse
{
// $ctx->methodName — 'user.update'
// $ctx->requestId — X-Request-Id header or auto-generated
// $ctx->user — Symfony security user (?UserInterface)
// $ctx->roles — list<string>
}