Lab 12: gRPC PHP

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm php:8.3-cli bash

Overview

gRPC is a high-performance RPC framework using Protocol Buffers for serialization and HTTP/2 for transport. This lab covers installing the gRPC PHP extension, defining proto3 messages, implementing client stubs, and handling errors.


Step 1: Setup — gRPC & Protobuf

# Install system dependencies
apt-get update && apt-get install -y git libssl-dev zlib1g-dev

# Install Composer
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# Create project
mkdir /tmp/grpclab && cd /tmp/grpclab

# Install gRPC and Protobuf PHP packages
composer require grpc/grpc google/protobuf --no-interaction

# Note: grpc/grpc requires the grpc PHP extension for actual RPC calls
# For pure PHP demo, we use the protobuf library for message serialization

Step 2: Proto3 Message Definitions (Inline PHP)

In production, you'd use protoc (Protocol Buffer compiler) to generate PHP classes from .proto files. For this lab, we implement the generated classes directly.

Equivalent .proto file:

⚠️ Note: Direct extension of \Google\Protobuf\Internal\Message requires specific protoc-generated infrastructure. In practice, always use protoc --php_out to generate classes. For this lab, we use a plain PHP approach to demonstrate the concepts.


Step 3: Plain PHP Proto Messages (No Extension Required)


Step 4: gRPC Status Codes


Step 5: Service Interface & In-Memory Implementation


Step 6: Client Stub


Step 7: Unary Call Demo

📸 Verified Output:


Step 8: Capstone — gRPC Interceptor & Metadata

📸 Verified Output:


Summary

Concept
In PHP
Notes

Proto messages

Classes extending Message or plain PHP

protoc --php_out generates in production

Service definition

PHP interface

Mirrors .proto service

Server implementation

Implement interface

Handle requests, throw GrpcException

Client stub

Wraps service / \Grpc\BaseStub

Calls remote methods

Status codes

\Grpc\STATUS_* constants

0=OK, 5=NOT_FOUND, 16=UNAUTHENTICATED

Metadata

array $metadata parameter

Headers: auth, tracing, correlation IDs

Interceptor

Middleware pattern

Auth, logging, retry, tracing

Serialization

Protocol Buffers binary

composer require google/protobuf

Transport

HTTP/2 (via ext-grpc)

composer require grpc/grpc

Streaming

Client/Server/Bidi streaming

\Grpc\ServerStreamingCall etc

Last updated