Installation:
composer require agentsib/jsonrpc-bundle
Add to config/bundles.php:
return [
// ...
Agentsib\JsonRpcBundle\AgentsibJsonRpcBundle::class => ['all' => true],
];
Basic Configuration:
Edit config/packages/agentsib_json_rpc.yaml (auto-generated):
agentsib_json_rpc:
enabled: true
routes:
prefix: '/api/jsonrpc'
First Use Case: Create a controller to expose a JSON-RPC endpoint:
use Agentsib\JsonRpcBundle\Controller\JsonRpcController;
class MyJsonRpcController extends JsonRpcController
{
public function myMethodAction($param1, $param2 = null)
{
return ['result' => $param1 . ($param2 ?: '')];
}
}
Register the route in config/routes.yaml:
agentsib_json_rpc:
resource: "@AgentsibJsonRpcBundle/Resources/config/routing.yml"
prefix: /api
Testing:
Send a POST request to /api/jsonrpc with a payload:
{
"jsonrpc": "2.0",
"method": "myMethod",
"params": ["Hello"],
"id": 1
}
Extend JsonRpcController for all JSON-RPC endpoints.
Method Naming:
Action (e.g., getUserAction).get_user_data_action).Parameter Handling:
public function calculateAction($a, $b = null, array $options = [])
{
// $options will be parsed from JSON-RPC "params" array
}
Prefix Configuration:
Override the default /api/jsonrpc prefix in config/packages/agentsib_json_rpc.yaml:
agentsib_json_rpc:
routes:
prefix: '/custom/rpc'
Custom Routes:
Extend the bundle’s routing file (Resources/config/routing.yml) or override it entirely:
my_custom_rpc:
path: /rpc/v1
methods: [POST]
defaults: { _controller: 'AgentsibJsonRpcBundle:Default:jsonRpc' }
Symfony Security Integration:
Use Symfony’s built-in security system (e.g., @IsGranted("ROLE_ADMIN")) in controller methods.
Example:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
/**
* @Security("is_granted('ROLE_ADMIN')")
*/
public function adminMethodAction()
{
return ['data' => 'secret'];
}
Custom Auth Middleware:
Override the bundle’s JsonRpcListener to add custom logic:
// src/EventListener/CustomJsonRpcListener.php
namespace App\EventListener;
use Agentsib\JsonRpcBundle\Event\JsonRpcEvent;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class CustomJsonRpcListener
{
public function onJsonRpc(FilterControllerEvent $event)
{
$request = $event->getRequest();
if (!$request->headers->has('X-API-KEY')) {
throw new \RuntimeException('Invalid API key');
}
}
}
Register in services.yaml:
services:
App\EventListener\CustomJsonRpcListener:
tags:
- { name: kernel.event_listener, event: jsonrpc.on_request, method: onJsonRpc }
Custom Error Responses: Throw exceptions with custom error codes:
throw new \RuntimeException('Invalid input', 40001);
The bundle will convert this to a JSON-RPC error response:
{
"jsonrpc": "2.0",
"error": {
"code": 40001,
"message": "Invalid input"
},
"id": 1
}
Global Error Mapping:
Override the error mapper in services.yaml:
services:
agentsib_json_rpc.error_mapper:
class: App\Service\CustomErrorMapper
arguments: ['@agentsib_json_rpc.error_mapper.inner']
null as the id in the request to indicate a notification:
{
"jsonrpc": "2.0",
"method": "logEvent",
"params": {"event": "user_login"},
"id": null
}
Handle in controller:
public function logEventAction($data)
{
// No return value expected
file_put_contents('log.txt', json_encode($data));
}
Auto-Generated Config:
The bundle generates config/packages/agentsib_json_rpc.yaml on first install. Always check for overrides here before debugging.
Route Overrides: If routes aren’t working, ensure:
config/bundles.php.routing.yml file exists in Resources/config/ (create if missing).config/routes.yaml.Request Dumping:
Enable Symfony’s profiler (APP_DEBUG=true) to inspect incoming JSON-RPC requests in the toolbar.
Common Issues:
Action and is public.json_decode($request->getContent(), true) for manual parsing if needed.{
"jsonrpc": "2.0",
"method": "batchMethod",
"params": {
"calls": [
{"method": "method1", "params": [1]},
{"method": "method2", "params": [2]}
]
},
"id": 1
}
Implement in controller:
public function batchMethodAction($data)
{
$results = [];
foreach ($data['calls'] as $call) {
$results[$call['method']] = $this->{$call['method']}(...$call['params']);
}
return $results;
}
Custom Serializers: Override the serializer service to handle custom data types:
services:
agentsib_json_rpc.serializer:
class: App\Serializer\CustomJsonRpcSerializer
arguments: ['@jms_serializer']
Middleware: Add custom middleware to the JSON-RPC pipeline:
services:
app.json_rpc.middleware:
class: App\Middleware\JsonRpcMiddleware
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
Logging:
Enable request/response logging by extending the JsonRpcListener:
public function onJsonRpc(FilterControllerEvent $event)
{
$request = $event->getRequest();
$this->logger->info('JSON-RPC Request', [
'method' => $request->request->get('method'),
'params' => $request->request->get('params'),
]);
}
Input Validation: Always validate input in controller methods. Example with Symfony Validator:
use Symfony\Component\Validator\Validator\ValidatorInterface;
public function createUserAction($data, ValidatorInterface $validator)
{
$errors = $validator->validate($data);
if (count($errors)) {
throw new \InvalidArgumentException((string) $errors);
}
// Process data
}
Rate Limiting:
Combine with Symfony’s rate_limiter component or use a middleware like SymfonyRateLimiterBundle.
Symfony2 references with Symfony in service configurations.autowiring is configured in config/services.yaml if using dependency injection.How can I help you explore Laravel packages today?