PHPackages                             spiral/grpc-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. spiral/grpc-client

ActiveLibrary[API Development](/categories/api)

spiral/grpc-client
==================

gRPC client

1.0.0-rc2(2mo ago)41140.3k↑668.5%[1 PRs](https://github.com/spiral/grpc-client/pulls)2MITPHPPHP &gt;=8.1CI passing

Since Jul 31Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/spiral/grpc-client)[ Packagist](https://packagist.org/packages/spiral/grpc-client)[ Docs](https://spiral.dev)[ GitHub Sponsors](https://github.com/sponsors/spiral)[ RSS](/packages/spiral-grpc-client/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (31)Versions (9)Used By (2)

gRPC Client
===========

[](#grpc-client)

The package provides powerful and convenient functionality for making client gRPC requests through a simple and extensible interface.

Installation
------------

[](#installation)

```
composer require spiral/grpc-client -W
```

[![PHP](https://camo.githubusercontent.com/3fd502bf3e10eaa805bcc534ac4c42a84f742c5b3f6d21eeee257a4a13aa3d9f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f73706972616c2f677270632d636c69656e742e7376673f7374796c653d666c61742d737175617265266c6f676f3d706870)](https://packagist.org/packages/spiral/grpc-client)[![Latest Version on Packagist](https://camo.githubusercontent.com/89f6b469f9e50b3a17ce2ae95b97b2a00dc263b6d68d6392de512c95eb26d07d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73706972616c2f677270632d636c69656e742e7376673f7374796c653d666c61742d737175617265266c6f676f3d7061636b6167697374)](https://packagist.org/packages/spiral/grpc-client)[![License](https://camo.githubusercontent.com/4844a8bc57978c98c9c5c1a8b5a8fd9781c66e835d3b532d2d7ec6b293ac1e46/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73706972616c2f677270632d636c69656e742e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Total downloads](https://camo.githubusercontent.com/f1bf27548c3fd3c585e01378c49fd75f6dc4202cc2789a0d8b4a5b273fc3d4f8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73706972616c2f677270632d636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spiral/grpc-client/stats)

Note that the package requires [gRPC extension](https://pecl.php.net/package/gRPC) to be installed.

Documentation
-------------

[](#documentation)

### Public API

[](#public-api)

The package provides the following parts of the API:

- Integration classes for use with frameworks.
- Classes for convenient package configuration through DTOs.
- A set of basic [interceptors](https://spiral.dev/docs/framework-interceptors/).
- Several types of exceptions for error handling.

### Integration

[](#integration)

#### Spiral

[](#spiral)

Note

The [`spiral/roadrunner-bridge`](https://github.com/spiral/roadrunner-bridge) package includes the `spiral/grpc-client` package by default since version `4.0.0` and provides its integration and configuration flow.

Add the `\Spiral\Grpc\Client\Bridge\GrpcClientBootloader` bootloader to the list of bootloaders in the application configuration (usually it is `Kernel.php`).

#### Standalone Usage

[](#standalone-usage)

The `GrpcClient` class provides a lightweight, Guzzle-like API for making gRPC calls without any framework or DI container:

```
use Spiral\Grpc\Client\GrpcClient;

// Minimal — one endpoint, call service methods right away
$client = GrpcClient::create('localhost:9001');
$mailSender = $client->service(\GRPC\MyService\MailSenderInterface::class);
$mailSender->sendMail($ctx, $request);
```

Add interceptors using the convenient `createConfig()` factories:

```
use Spiral\Grpc\Client\GrpcClient;
use Spiral\Grpc\Client\Interceptor\SetTimeoutInterceptor;
use Spiral\Grpc\Client\Interceptor\RetryInterceptor;

$client = GrpcClient::create('localhost:9001')
    ->withInterceptors([
        SetTimeoutInterceptor::createConfig(10_000),
        RetryInterceptor::createConfig(maximumAttempts: 3),
    ]);
```

Multiple connections for failover:

```
$client = GrpcClient::create(['localhost:9001', 'localhost:9002']);
```

`ConnectionConfig` for TLS:

```
use Spiral\Grpc\Client\Config\ConnectionConfig;
use Spiral\Grpc\Client\Config\TlsConfig;

$client = GrpcClient::create(
    new ConnectionConfig('localhost:9001', tls: new TlsConfig(
        certChain: '/my-project.pem',
        privateKey: '/my-project.key',
    )),
);
```

With a factory (e.g. Spiral's container) to resolve class-string interceptors via DI:

```
$client = GrpcClient::create('localhost:9001')
    ->withFactory($factory);
```

The `with*` methods are immutable — each returns a new instance, so you can safely derive pre-configured clients:

```
$base = GrpcClient::create('localhost:9001')
    ->withInterceptors([SetTimeoutInterceptor::createConfig(5_000)]);

$withRetry = $base->withInterceptors([
    SetTimeoutInterceptor::createConfig(5_000),
    RetryInterceptor::createConfig(maximumAttempts: 3),
]);
```

Note

`GrpcClient` does not support per-service interceptors. If you need that, use `ServiceClientProvider` with the full `GrpcClientConfig` / `ExecuteServiceInterceptors` setup.

#### Other Frameworks

[](#other-frameworks)

If you are using this package with another framework, you can use `\Spiral\Grpc\Client\ServiceClientProvider` with a `GrpcClientConfig`to get ready-to-use gRPC clients, or use the standalone `GrpcClient` described above.

### Configuration DTOs

[](#configuration-dtos)

Now let's consider a configuration example:

```
use Spiral\Grpc\Client\Config\GrpcClientConfig;
use Spiral\Grpc\Client\Config\ServiceConfig;
use Spiral\Grpc\Client\Config\ConnectionConfig;
use Spiral\Grpc\Client\Interceptor\SetTimeoutInterceptor;
use Spiral\Grpc\Client\Interceptor\RetryInterceptor;
use Spiral\Grpc\Client\Interceptor\ExecuteServiceInterceptors;

new GrpcClientConfig(
    interceptors: [
        SetTimeoutInterceptor::createConfig(10_000), // 10 seconds
        RetryInterceptor::createConfig(
            maximumAttempts: 3,
            initialInterval: 100, // 0.1 seconds
            backoffCoefficient: 1.5,
        ),
        ExecuteServiceInterceptors::class,
    ],
    services: [
        new ServiceConfig(
            connections: new ConnectionConfig('my-service:9001'),
            interfaces: [
                \GRPC\MyService\MailSenderInterface::class,
                \GRPC\MyService\BlackListInterface::class,
                \GRPC\MyService\SubscriberInterface::class,
            ],
        ),
    ],
)
```

#### GrpcClientConfig

[](#grpcclientconfig)

This class represents the configuration of the gRPC client in general. It includes a list of service configurations and a general list of interceptors that will be applied to all services.

Interceptors can be declared as class names, `Spiral\Core\Container\Autowire` objects (if custom constructor arguments need to be passed), or objects. Note that some interceptors provide convenient methods for creating configurations.

#### ServiceConfig

[](#serviceconfig)

This class represents the configuration of a specific service or a group of similar services but with different connection options.

The `interfaces` parameter is a list of gRPC service interfaces that were generated by the `protoc` utility and that are implemented by the service.

Note

Currently, we support only service interfaces that are [generated](https://spiral.dev/docs/grpc-client)using the `protoc` utility with the `protoc-gen-php-grpc` plugin.

The configuration example above doesn't include the `interceptors` parameter. It's the same as in the general configuration, but it's applied only to the specified service. This branch of interceptors is run via the `ExecuteServiceInterceptors` interceptor. So, it's important to include it if you want to use service-specific interceptors.

The `connections` parameter is a list of connection configurations. You can specify multiple connections to distribute the load between them or to provide fail-over. Multi-connection orchestration strategy can be configured by interceptors, for example, `ConnectionsRotationInterceptor`.

#### ConnectionConfig

[](#connectionconfig)

This class represents the configuration of a single connection to the gRPC service. It includes credentials and the service address.

To create a secure connection, use the `TlsConfig` class.

```
new ConnectionConfig(
    address: 'my-service:9001',
    tls: new TlsConfig(
        privateKey: '/my-project.key',
        certChain: '/my-project.pem',
    ),
),
```

### Usage

[](#usage)

After the integration and configuration are ready, you can get the client for the desired service interface from the container and call the service methods.

```
final class Sender
{
    public function __construct(
        private \GRPC\MyService\MailSenderInterface $mailSender,
    ) {}

    public function __invoke(string $email, $subject, string $message): bool
    {
        $request = (new \GRPC\MyService\SendMailRequest())
            ->setEmail($email)
            ->setSubject($subject)
            ->setMessage($message);

        $response = $this->mailSender->sendMail(new \Spiral\RoadRunner\GRPC\Context([]), $request);
        return $response->getSuccess();
    }
}
```

### Interceptors

[](#interceptors)

Important points when using interceptors in the [long-running](https://spiral.dev/docs/start-server) mode:

- **Stateful**: interceptors are recreated anew for each request, so you can safely store the state of each call.
- **Scoped**: interceptors are created in the same Container Scope in which the client is called. Accordingly, you can request contextual dependencies in the interceptor's constructor.

When writing your own interceptors, you will likely want to work with gRPC-specific fields (options, metadata, input message, etc.). Use the `\Spiral\Grpc\Client\Interceptor\Helper` class to get or set the values of these context fields.

```
final class AuthContextInterceptor implements InterceptorInterface
{
    public function __construct(
        private readonly AuthContextInterface $authContext,
    ) {}

    public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed
    {
        $token = $this->authContext->getToken();

        if ($token === null) {
            return $handler->handle($context);
        }

        $metadata = \Spiral\Grpc\Client\Interceptor\Helper::withMetadata($context);
        $metadata['auth-token'] = [$token];

        return $handler->handle(\Spiral\Grpc\Client\Interceptor\Helper::withMetadata($context, $metadata));
    }
}
```

#### Order of Interceptors

[](#order-of-interceptors)

Interceptors are executed in the order in which they are declared in the configuration. The order of the interceptors is important.

For example, if we have the following configuration:

1. `SetTimeout(10 seconds)`
2. `Retry(maxAttempts: 3, interval: 2 seconds)`
3. `SetTimeout(3 seconds)`

then we will have a 3-second timeout for each retry attempt.
We also have a 10-second timeout for all attempts in total, after which **no new request** attempts will be made. This happens because the `RetryInterceptor` takes into account previously configured timeouts.

Also, the placement of the `ExecuteServiceInterceptors` interceptor, which embeds the interceptors of the currently running service, will affect the final sequence of interceptors.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance88

Actively maintained with recent releases

Popularity45

Moderate usage in the ecosystem

Community11

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~149 days

Total

5

Last Release

60d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/796136?v=4)[Anton Tsitou](/maintainers/wolfy-j)[@wolfy-j](https://github.com/wolfy-j)

---

Top Contributors

[![roxblnfk](https://avatars.githubusercontent.com/u/4152481?v=4)](https://github.com/roxblnfk "roxblnfk (39 commits)")

---

Tags

grpcgrpc-clientphp

###  Code Quality

TestsPest

Static AnalysisPsalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/spiral-grpc-client/health.svg)

```
[![Health](https://phpackages.com/badges/spiral-grpc-client/health.svg)](https://phpackages.com/packages/spiral-grpc-client)
```

###  Alternatives

[google/gax

Google API Core for PHP

265103.1M454](/packages/google-gax)[temporal/sdk

Temporal SDK

4002.2M18](/packages/temporal-sdk)[google/grpc-gcp

gRPC GCP library for channel management

18497.8M3](/packages/google-grpc-gcp)[googleads/google-ads-php

Google Ads API client for PHP

3497.6M9](/packages/googleads-google-ads-php)[clarifai/clarifai-php-grpc

Clarifai PHP gRPC client

1128.3k](/packages/clarifai-clarifai-php-grpc)[passkit/passkit-php-grpc-sdk

PHP gRPC SDK for Apple Wallet and Google Pay Membership / Loyalty / Access Cards, Coupons, Flights &amp; Event-Tickets.

132.0k](/packages/passkit-passkit-php-grpc-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
