RPC: Connect, gRPC-Web and gRPC
HexaGen PHP answers RPC calls defined in .proto files, in pure PHP: no grpc extension, no Go, no Envoy proxy. It works on FrankenPHP, PHP-FPM or any other server.
One service class answers three wire protocols:
| Protocol | Content type | Clients |
|---|---|---|
| Connect | application/proto, application/json | connect-go, connect-es (browser and Node), connect-swift, connect-kotlin, and curl |
| gRPC-Web | application/grpc-web[+proto|+json], application/grpc-web-text | grpc-web (browser), connect-go, connect-es |
| gRPC | application/grpc[+proto|+json] | Error responses only, see Limits |
Each call is unary (one request, one reply), with binary protobuf or JSON messages. The examples below were verified with the official connect-go client in every protocol and codec.
Enable it
RPC is off by default. Turn it on in .env:
GRPC_ENABLED=trueRPC calls then go through the global middlewares (authentication, rate limiting, security headers, CORS), exactly like any other request. When a middleware rejects a call, the client gets a status it understands: a 401 becomes unauthenticated, a 429 becomes resource_exhausted, and so on.
Generate a service
make:grpc creates the contract and the handler inside a slice:
php hexaphp make:grpc Flights| File | What it is |
|---|---|
src/Slices/Flights/Proto/flights.proto | The contract: package flights, service FlightService with a GetFlight method |
src/Slices/Flights/Controller/FlightsGrpcController.php | The typed handler. If the slice has a Flight model, it looks the row up and answers not_found when it is missing |
generated/Proto/Flights/*.php | The message classes, written by protoc |
If protoc is installed, the command runs it. Otherwise it prints the exact command. Run it again whenever you change the .proto file:
protoc --proto_path=src/Slices/Flights/Proto --php_out=generated flights.protoThe generated classes live in the Proto namespace. Apps created from rbaezc/hexagen-app 1.2 or later already autoload it. In older apps, add this to composer.json and run composer dump-autoload:
"autoload": { "psr-4": { "Proto\\": "generated/Proto/" } }Use --service=Schedule to name the service, and --no-protoc to skip running protoc. The proto package is the slice name in lowercase, so the call path is /flights.FlightService/GetFlight.
A service in a slice
Write the contract in a .proto file and generate the PHP message classes with protoc --php_out (install google/protobuf in your app):
syntax = "proto3";
package flights;
option php_namespace = "Proto\\Flights";
option php_metadata_namespace = "Proto\\Flights\\Metadata";
service FlightService {
rpc Search (SearchRequest) returns (SearchReply);
}
message SearchRequest { string origin = 1; }
message SearchReply { int32 count = 1; }Then answer it from the slice. Methods take and return the generated message classes; the framework decodes the request and encodes the reply in whatever codec the client used, binary or JSON:
<?php
namespace HexaGen\Slices\Flights\Controller;
use Proto\Flights\SearchReply;
use Proto\Flights\SearchRequest;
use HexaGen\Core\Rpc\Code;
use HexaGen\Core\Rpc\RpcException;
use HexaGen\Slices\Flights\Domain\Flight;
use Symfony\Component\HttpFoundation\Request;
class FlightsGrpcController
{
public function Search(SearchRequest $request, Request $http): SearchReply
{
if ($request->getOrigin() === '') {
throw new RpcException(Code::InvalidArgument, 'origin is required');
}
$count = count(Flight::query()->where('origin', $request->getOrigin())->get());
return new SearchReply(['count' => $count]);
}
}- The first parameter is the request message.
- Add a parameter typed
Symfony\Component\HttpFoundation\Requestto read headers or metadata, for example$http->headers->get('Authorization'). - A method typed
string $message): stringstill works. It receives the raw payload and returns raw bytes in the client's codec. - Classes registered in the container are resolved through it, so constructor dependencies are injected.
Calling it
With Connect, a call is a plain POST, so curl works:
curl -X POST http://localhost:8000/flights.FlightService/Search \
-H 'Content-Type: application/json' \
-H 'Connect-Protocol-Version: 1' \
-d '{"origin": "MEX"}'
# {"count":3}From Go, with connect-go:
client := connect.NewClient[flightsv1.SearchRequest, flightsv1.SearchReply](
http.DefaultClient,
"https://api.example.com/flights.FlightService/Search",
// connect.WithGRPCWeb(), // or gRPC-Web
)
res, err := client.CallUnary(ctx, connect.NewRequest(&flightsv1.SearchRequest{Origin: "MEX"}))From the browser, with connect-es (createConnectTransport or createGrpcWebTransport), pointing baseUrl at your app.
Routing
The request path is /<package.Service>/<Method>. The kernel looks for the class in this order:
| Path | Class |
|---|---|
/Billing/Charge | HexaGen\Grpc\Billing |
/flights.FlightService/Search | HexaGen\Slices\Flights\Controller\FlightsGrpcController |
The first segment before the dot names the slice. Only identifiers are accepted: the service must match [A-Za-z_][A-Za-z0-9_.]* and the method [A-Za-z][A-Za-z0-9_]*. Only public, non-static methods are called, never magic methods.
Errors
Throw RpcException to answer with a specific code. Its message is sent to the client, so keep it safe to show:
throw new RpcException(Code::NotFound, 'Flight not found');Any other exception is reported through the exception handler, and the client receives internal with the message Internal error. The exception's own message is never sent.
| Situation | Code |
|---|---|
| Invalid path, malformed frame or message | invalid_argument (3) |
| Unknown service or method, unsupported codec or compression | unimplemented (12) |
| Message over the size limit | resource_exhausted (8) |
| Exception in your method | internal (13) |
Connect returns errors as JSON with the matching HTTP status (404 for not_found, for example). gRPC-Web puts the code in its trailer frame, and gRPC in the grpc-status header.
Browsers: CORS and CSRF
With GRPC_ENABLED=true, the CORS middleware adds the headers RPC clients need (Connect-Protocol-Version, X-Grpc-Web, Grpc-Timeout...) and exposes Grpc-Status and Grpc-Message. You only list your frontend in CORS_ALLOWED_ORIGINS. Preflight requests to RPC paths are answered even though they have no router route.
RPC calls do not need a CSRF token. Their content types are not CORS-safelisted, so a cross-site form cannot send them, and a cross-site script needs a preflight that CORS controls.
Limits
- Unary only. Streaming calls are not supported.
- Message size. Requests over 4 MB are rejected. Change it with
grpc.max_message_bytesin your config. - Compression. Requests may be gzip-compressed (
Content-Encoding: gzipfor Connect,grpc-encoding: gzipfor gRPC and gRPC-Web). Replies are not compressed. - Timeouts.
grpc-timeoutandConnect-Timeout-Msare not enforced; use your server's request timeout. - gRPC clients. A successful gRPC reply needs HTTP/2 trailers, and PHP cannot write them. Strict gRPC clients (grpc-go, grpcurl) therefore reject successful replies, although errors reach them correctly. Use Connect or gRPC-Web clients instead; they exist for Go, TypeScript, Swift and Kotlin, and connect-go can call any gRPC-Web or Connect server.