PHP code example of projectsaturnstudios / json-rpc

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

    

projectsaturnstudios / json-rpc example snippets




namespace App\Http\Controllers\RPC;

use JSONRPC\Attributes\MethodController;
use JSONRPC\Rpc\Controllers\RpcController;
use JSONRPC\RPCRequest;
use JSONRPC\RPCResponse;

#[MethodController('math')]
class MathController extends RpcController
{
    public function handle(RPCRequest $request): RPCResponse
    {
        // Handle the main 'math' method
        return new RPCResponse(
            id: $request->id,
            result: ['message' => 'Math service is running', 'available_operations' => ['add', 'subtract', 'multiply', 'divide']]
        );
    }
    
    public function add(RPCRequest $request): RPCResponse
    {
        // Handle 'math/add' method
        $params = $request->params;
        
        if (!isset($params[0]) || !isset($params[1])) {
            return new RPCResponse(
                id: $request->id,
                error: new RPCErrorObject(
                    code: RPCErrorCode::INVALID_PARAMS,
                    message: 'Two numbers are 



use JSONRPC\Support\Facades\Rpc;
use App\Http\Controllers\RPC\MathController;
use App\Http\Controllers\RPC\WeatherController;
use App\Http\Controllers\RPC\TodoController;

// Register RPC method controllers
Rpc::method('math', MathController::class);
Rpc::method('weather', WeatherController::class);
Rpc::method('todo', TodoController::class);

// You can also register namespaced methods
Rpc::method('api/calculator', MathController::class);

use JSONRPC\RPCRequest;
use JSONRPC\Support\Facades\RPCRouter;

$request = new RPCRequest(
    method: 'math/add',
    params: [5, 3],
    id: 1
);

$response = RPCRouter::dispatch($request);
echo $response->toJsonRpc();
// {"jsonrpc":"2.0","id":1,"result":8}

use JSONRPC\RPCRequest;
use JSONRPC\RPCResponse;

// Create a request
$request = new RPCRequest(
    method: 'math/multiply',
    params: [4, 7],
    id: 1
);

// Create a successful response
$response = new RPCResponse(
    id: 1,
    result: 28
);

// Output JSON-RPC
echo $response->toJsonRpc();
// {"jsonrpc":"2.0","id":1,"result":28}

use JSONRPC\RPCResponse;
use JSONRPC\RPCErrorObject;
use JSONRPC\Enums\RPCErrorCode;

// Create an error response
$response = new RPCResponse(
    id: 1,
    error: new RPCErrorObject(
        code: RPCErrorCode::INVALID_PARAMS,
        message: 'Invalid parameters provided',
        data: ['expected' => 'array of numbers', 'received' => 'string']
    )
);

use JSONRPC\RPCNotification;

// Create a notification (no response expected)
$notification = new RPCNotification(
    method: 'logger/info',
    params: ['message' => 'User logged in', 'user_id' => 123]
);

echo $notification->toJsonRpc();
// {"jsonrpc":"2.0","method":"logger/info","params":{"message":"User logged in","user_id":123}}



namespace App\Http\Controllers\RPC;

use JSONRPC\Attributes\MethodController;
use JSONRPC\Rpc\Controllers\RpcController;
use JSONRPC\RPCRequest;
use JSONRPC\RPCResponse;
use JSONRPC\RPCErrorObject;
use JSONRPC\Enums\RPCErrorCode;

#[MethodController('weather')]
class WeatherController extends RpcController
{
    public function handle(RPCRequest $request): RPCResponse
    {
        // Default handler for 'weather'
        return new RPCResponse(
            id: $request->id,
            result: ['service' => 'weather', 'available_methods' => ['current', 'forecast', 'alerts']]
        );
    }
    
    public function current(RPCRequest $request): RPCResponse
    {
        try {
            $params = $request->params;
            
            // Validate w RPCErrorObject(
                    code: RPCErrorCode::INTERNAL_ERROR,
                    message: 'Weather service unavailable'
                )
            );
        }
    }
    
    private function getCurrentWeather(string $location): array
    {
        // Your actual weather API logic
        return [
            'location' => $location,
            'temperature' => 72,
            'condition' => 'sunny',
            'humidity' => 45
        ];
    }
}



use JSONRPC\Support\Facades\Rpc;
use App\Http\Controllers\RPC\MathController;
use App\Http\Controllers\RPC\WeatherController;
use App\Http\Controllers\RPC\TodoController;

// Basic method registration
Rpc::method('math', MathController::class);
Rpc::method('weather', WeatherController::class);
Rpc::method('todo', TodoController::class);

// Namespaced methods
Rpc::method('api/calculator', MathController::class);
Rpc::method('api/weather', WeatherController::class);

// Grouped registration
Rpc::method('services/math', MathController::class);
Rpc::method('services/weather', WeatherController::class);

use JSONRPC\Support\Facades\Rpc;
use JSONRPC\Support\Facades\RPCRouter;
use App\Http\Controllers\RPC\MathController;

// Using the Rpc facade
Rpc::method('math', MathController::class);

// Or using the RPCRouter facade directly
RPCRouter::addMethod(new MathController());



return [
    'registration' => [
        'driver' => 'default',
        'drivers' => [
            'default' => [
                // Driver-specific configuration
            ],
        ]
    ]
];

new RPCRequest(
    method: string,           // Required: The method to call
    params: ?array = null,    // Optional: Method parameters
    id: string|int|null = null // Optional: Request ID (null for notifications)
)

new RPCResponse(
    id: string|int,                    // Required: Request ID
    result: string|array|null = null,  // Optional: Success result
    error: ?RPCErrorObject = null      // Optional: Error object
)

new RPCNotification(
    method: string,        // Required: The method to call
    params: ?array = null  // Optional: Method parameters
)

new RPCErrorObject(
    code: RPCErrorCode,  // Required: Error code
    message: string,     // Required: Error message
    data: mixed = null   // Optional: Additional error data
)
bash
php artisan vendor:publish --provider="JSONRPC\Providers\JSONRPCServiceProvider"