PHP code example of cleatsquad / php-grpc-frame-codec

1. Go to this page and download the library: Download cleatsquad/php-grpc-frame-codec 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/ */

    

cleatsquad / php-grpc-frame-codec example snippets


use CleatSquad\GrpcFrameCodec\GrpcFrameCodec;

$codec = new GrpcFrameCodec();

// Your backend receives the raw protobuf request body directly — no
// decode() needed on the way in.
$requestBytes = file_get_contents('php://input');

// ... decode $requestBytes with your generated protobuf message class,
// handle the call, encode the response message ...

// Frame the response before sending it back:
header('Content-Type: ' . GrpcFrameCodec::CONTENT_TYPE);
echo $codec->encode($responseBytes);

use CleatSquad\GrpcFrameCodec\GrpcFrameCodec;

$codec = new GrpcFrameCodec();
$buffer = '';

foreach ($chunksAsTheyArrive as $chunk) {
    $buffer .= $chunk;

    while (($payload = $codec->readNextFrame($buffer)) !== null) {
        handle($payload); // one decoded message
    }
}

// public/index.php
// nginx forwards POST /{package}.{Service}/{Method} to this script via fastcgi_pass
use CleatSquad\GrpcFrameCodec\GrpcFrameCodec;

$codec = new GrpcFrameCodec();
$requestBytes = file_get_contents('php://input');

$responseBytes = handle($_SERVER['REQUEST_URI'], $requestBytes); // your dispatch + business logic

header('Content-Type: application/grpc+proto');
echo $codec->encode($responseBytes);

use CleatSquad\GrpcFrameCodec\GrpcFrameCodec;
use Spiral\RoadRunner\Http\PSR7Worker;

$codec = new GrpcFrameCodec();

while ($request = $psr7Worker->waitRequest()) {
    $requestBytes = (string) $request->getBody();
    $responseBytes = handle($request->getUri()->getPath(), $requestBytes);

    $response = new \Nyholm\Psr7\Response(200, ['Content-Type' => 'application/grpc+proto'], $codec->encode($responseBytes));
    $psr7Worker->respond($response);
}

// public/index.php — same code as the nginx+PHP-FPM example, FrankenPHP
// is just the server process running it (worker mode or classic).