bankiru/jsonrpc-server-bundle
Installation
composer require bankiru/jsonrpc-server-bundle
Add to config/bundles.php:
return [
// ...
Bankiru\JsonRpcServerBundle\BankiruJsonRpcServerBundle::class => ['all' => true],
];
Basic Configuration
Edit config/packages/bankiru_json_rpc_server.yaml:
bankiru_json_rpc_server:
routes:
jsonrpc: /api/jsonrpc
First Endpoint Create a service to handle RPC calls:
// src/Service/MyRpcService.php
namespace App\Service;
use Bankiru\RpcServerBundle\Annotation\RpcMethod;
class MyRpcService
{
/**
* @RpcMethod("add")
*/
public function add(int $a, int $b): int
{
return $a + $b;
}
}
Test with cURL
curl -X POST http://your-app/api/jsonrpc \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "add", "params": [5, 3], "id": 1}'
Expected response:
{"jsonrpc":"2.0","result":8,"id":1}
Annotated Methods
Use @RpcMethod annotation to expose methods:
/**
* @RpcMethod("user.create", description="Creates a new user")
* @RpcMethod("user.update", description="Updates an existing user")
*/
public function handleUser($action, array $data)
{
// Logic here
}
Dependency Injection Inject services into RPC handlers:
public function __construct(private UserRepository $userRepo) {}
/**
* @RpcMethod("user.get")
*/
public function getUser(int $id): array
{
return $this->userRepo->find($id);
}
Request/Response Handling Access raw request/response via events:
// src/EventListener/RpcListener.php
use Bankiru\JsonRpcServerBundle\Event\JsonRpcEvent;
public function onJsonRpc(JsonRpcEvent $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
}
Custom Routes Override default route in config:
bankiru_json_rpc_server:
routes:
jsonrpc: /v1/rpc
Authentication
Use Symfony middleware (e.g., ApiKeyAuthenticator):
# config/packages/security.yaml
security:
firewalls:
jsonrpc:
pattern: ^/api/jsonrpc
stateless: true
json_login:
check_path: /api/jsonrpc/login
CORS Configuration
Add to config/packages/nelmio_cors.yaml:
nelmio_cors:
defaults:
allow_origin: ["*"]
paths:
'^/api/jsonrpc':
allow_origin: ["*"]
allow_methods: ["POST"]
allow_headers: ["Content-Type"]
max_age: 3600
Custom Errors Throw exceptions with specific codes:
throw new \RuntimeException("Invalid input", 1001);
Map to JSON-RPC errors via event subscriber:
public function onJsonRpcError(JsonRpcErrorEvent $event)
{
$event->setErrorCode(1001);
$event->setErrorMessage("Custom error message");
}
Validation Use Symfony Validator:
use Symfony\Component\Validator\Constraints as Assert;
/**
* @RpcMethod("user.create")
* @param array $data {
* @Assert\NotBlank()
* string name
* }
*/
public function createUser(array $data)
{
// ...
}
Annotation Parsing
@RpcMethod not recognized.bankiru/rpc-server-bundle is installed and autoloaded.
composer require bankiru/rpc-server-bundle
php bin/console cache:clear
Serialization Conflicts
rpc.view event:
public function onRpcView(RpcViewEvent $event)
{
$event->setData(json_encode($event->getData()));
}
Circular References
JsonSerializable or custom serializer:
class User implements JsonSerializable
{
public function jsonSerialize()
{
return ['id' => $this->id, 'name' => $this->name];
}
}
Deprecated Methods
JsonRpcRequestInterface not found.Bankiru\RpcServerBundle\Request\JsonRpcRequest instead.Enable Verbose Logging
Add to config/packages/monolog.yaml:
handlers:
json_rpc:
type: stream
path: "%kernel.logs_dir%/jsonrpc.log"
level: debug
channels: ["json_rpc"]
Inspect Events Dump events in a subscriber:
public function onJsonRpc(JsonRpcEvent $event)
{
\Symfony\Component\Debug\Debug::dump($event->getRequest()->getContent());
}
Test with Postman Use Postman to send raw JSON-RPC requests and inspect responses.
Custom Serializers Override default JSON serializer:
// src/Serializer/CustomJsonSerializer.php
use Bankiru\JsonRpcServerBundle\Serializer\JsonSerializerInterface;
class CustomJsonSerializer implements JsonSerializerInterface
{
public function serialize($data)
{
return json_encode($data, JSON_PRETTY_PRINT);
}
}
Register as service:
services:
Bankiru\JsonRpcServerBundle\Serializer\JsonSerializerInterface: '@App\Serializer\CustomJsonSerializer'
Dynamic Method Loading
Use RpcMethodLoaderInterface to load methods dynamically:
public function loadMethods()
{
return [
'dynamic.method' => [$this, 'handleDynamicMethod'],
];
}
Middleware Stack Add custom middleware:
// src/Middleware/RpcLoggingMiddleware.php
use Bankiru\JsonRpcServerBundle\Middleware\RpcMiddlewareInterface;
class RpcLoggingMiddleware implements RpcMiddlewareInterface
{
public function handle(JsonRpcRequest $request, callable $next)
{
// Pre-processing
$response = $next($request);
// Post-processing
return $response;
}
}
Register in config:
bankiru_json_rpc_server:
middleware:
- App\Middleware\RpcLoggingMiddleware
Caching RPC Methods Cache method metadata to avoid repeated annotation parsing:
// src/Cache/RpcMethodCache.php
use Doctrine\Common\Cache\CacheProvider;
class RpcMethodCache implements CacheProvider
{
public function fetch($id)
{
// Implement caching logic
}
}
Configure in config/packages/bankiru_json_rpc_server.yaml:
bankiru_json_rpc_server:
cache: App\Cache\RpcMethodCache
Batch Processing Handle batch requests efficiently:
/**
* @RpcMethod("batch.process")
*/
public function processBatch(array $operations)
{
$results = [];
foreach ($operations as $op) {
$results[] = $this->executeOperation($op);
}
return $results;
}
How can I help you explore Laravel packages today?