# PHP SDK

> How to write a service's contract from its PHP code with the PHP SDK: installation, an example with attributes and docblock tags, the GraphQL consumer and graph, the generate command and the flow to publish. The full reference is the SDK's README.

The PHP SDK writes the [contract file](https://bidirekt.com/docs/contracts/the-contract-file.md) of a service from its PHP code. You annotate the schemas and the handlers that provide or consume each REST resource, or call a GraphQL API, with attributes or with `@bidirekt` tags in docblocks, run `generate`, and get `contracts/generated.yaml`, which [`validate`](https://bidirekt.com/docs/ship/validate.md) and [`publish`](https://bidirekt.com/docs/ship/publish.md) take like any other contract file. It reads the source code and never runs your app.

This page shows how it reads. Every attribute argument, tag, type and error is in the [SDK's README](https://github.com/bidirekt/php-sdk#readme).

## Install

The SDK needs PHP 8.0 or later and Composer 2.2 or later. Install it as a dev dependency:

```
$ composer require --dev bidirekt/php-sdk
```

When Composer says your lock file pins an older `nikic/php-parser` (a Laravel project locks it through `psy/psysh`), let it update that package too:

```
$ composer require --dev bidirekt/php-sdk -W
```

An attribute runs nothing, so a production install with `composer install --no-dev`, which leaves the package out, still runs your app. `new BidirektField(...)` inside an attribute needs PHP 8.1 to run your app, as does an enum, and `Enum::Case->value` as an attribute argument PHP 8.2; [Installation](https://github.com/bidirekt/php-sdk#installation) in the README has the details.

## Example

`petstore_php` is a Slim service. It provides `GET /pets`, `GET /pets/*` and `POST /pets`, and consumes `GET /ratings/*` from `petstore_reviews`. `#[BidirektSchema]` marks each schema and `#[BidirektField]` each field of the contract; a field without it stays out of the contract. `Pet` uses each kind of field:

```php
<?php
// src/Pet.php

namespace App;

use Bidirekt\PhpSdk\BidirektField;
use Bidirekt\PhpSdk\BidirektSchema;

#[BidirektSchema]
final class Pet
{
    /**
     * @param list<string> $tags
     * @param array<string, string> $notes
     */
    public function __construct(
        #[BidirektField]
        public int $id,

        #[BidirektField]
        public string $name,

        #[BidirektField]
        public PetStatus $status,

        #[BidirektField]
        public Owner $owner,

        #[BidirektField]
        public array $tags,

        #[BidirektField]
        public array $notes,

        #[BidirektField(type: 'float', description: 'In kilograms')]
        public float $weight,

        #[BidirektField]
        public ?string $birthDate,

        #[BidirektField(
            union: [
                'person' => Owner::class,
                'shelter' => Shelter::class,
            ],
        )]
        public Owner|Shelter $adoptedFrom,
    ) {}

    #[BidirektField(optional: true)]
    public string $nickname;
}
```

`Owner`, `Shelter` and `NewPet` are schema classes like it, with one string field each (`Owner::$name`, `Shelter::$city` and `NewPet::$name`), `Rating` has a `float $average` and an `int $count`, and `PetStatus` is an enum with the string values `available` and `adopted`.

`#[BidirektRestProvider]` on a handler declares what it provides. Slim routes `/pets/{id}` to `show`, and the path is declared `/pets/*`: a `*` for each dynamic segment, never the framework's placeholder. `request` names the body the handler reads, and a body is a schema class, `[Pet::class]` for a list of it, or `null` for no body:

```php
<?php
// src/PetController.php

namespace App;

use Bidirekt\PhpSdk\BidirektRestProvider;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

final class PetController
{
    public function __construct(private PetRepository $pets) {}

    #[BidirektRestProvider(
        method: 'GET',
        path: '/pets',
        responses: [200 => [Pet::class]],
    )]
    public function index(Request $request, Response $response): Response
    {
        return self::json($response, $this->pets->all());
    }

    #[BidirektRestProvider(
        method: 'GET',
        path: '/pets/*',
        responses: [
            200 => Pet::class,
            404 => null,
        ],
    )]
    public function show(
        Request $request,
        Response $response,
        array $args,
    ): Response {
        $pet = $this->pets->find((int) $args['id']);
        if ($pet === null) {
            return $response->withStatus(404);
        }

        return self::json($response, $pet);
    }

    #[BidirektRestProvider(
        method: 'POST',
        path: '/pets',
        request: NewPet::class,
        responses: [
            201 => Pet::class,
            400 => null,
        ],
    )]
    public function create(Request $request, Response $response): Response
    {
        $name = $request->getParsedBody()['name'] ?? null;
        if (!is_string($name)) {
            return $response->withStatus(400);
        }

        return self::json($response->withStatus(201), $this->pets->add($name));
    }

    private static function json(Response $response, mixed $body): Response
    {
        $response->getBody()->write(
            (string) json_encode($body, JSON_PRESERVE_ZERO_FRACTION),
        );

        return $response->withHeader('Content-Type', 'application/json');
    }
}
```

`#[BidirektRestConsumer]` declares what a client consumes, and from which provider:

```php
<?php
// src/ReviewsClient.php

namespace App;

use Bidirekt\PhpSdk\BidirektRestConsumer;
use GuzzleHttp\Client;

final class ReviewsClient
{
    public function __construct(private Client $http) {}

    #[BidirektRestConsumer(
        provider: 'petstore_reviews',
        method: 'GET',
        path: '/ratings/*',
        responses: [
            200 => Rating::class,
            404 => null,
        ],
    )]
    public function rating(int $petId): ?Rating
    {
        $response = $this->http->get(
            "/ratings/{$petId}",
            ['http_errors' => false],
        );
        $body = json_decode((string) $response->getBody(), true);

        if ($response->getStatusCode() === 404) {
            return null;
        }

        return new Rating($body['average'], $body['count']);
    }
}
```

Run `generate` in the project folder, the one with `composer.json`:

```
$ vendor/bin/php-sdk generate
```

It writes `contracts/generated.yaml`. The list `[Pet::class]` becomes the `PetList` schema:

```yaml
# Generated by bidirekt/php-sdk. Do not edit.
provides:
  rest:
    /pets:
      get:
        responses:
          200: PetList
      post:
        request: NewPet
        responses:
          201: Pet
          400: ~
    /pets/*:
      get:
        responses:
          200: Pet
          404: ~
consumes:
  petstore_reviews:
    rest:
      /ratings/*:
        get:
          responses:
            200: Rating
            404: ~
schemas:
  NewPet:
    type: object
    properties:
      name:
        type: string
  Owner:
    type: object
    properties:
      name:
        type: string
  Pet:
    type: object
    properties:
      id:
        type: integer
      name:
        type: string
      status:
        ref: PetStatus
      owner:
        ref: Owner
      tags:
        type: array
        items:
          type: string
      notes:
        type: map
        values:
          type: string
      weight:
        type: float
        description: In kilograms
      birthDate:
        type: string
        nullable: true
      adoptedFrom:
        type: union
        members:
          person:
            ref: Owner
          shelter:
            ref: Shelter
      nickname:
        type: string
        optional: true
  PetList:
    type: array
    items:
      ref: Pet
  PetStatus:
    type: enum
    members: ["available", "adopted"]
  Rating:
    type: object
    properties:
      average:
        type: number
      count:
        type: integer
  Shelter:
    type: object
    properties:
      city:
        type: string
```

An enum with string values is a `ref` to an `enum` schema, a schema class is a `ref`, and an `array` takes the type of its items from the PHPDoc: `list<string>` is a list, `array<string, string>` a map. `weight` declares `type: 'float'` because the controller encodes with `JSON_PRESERVE_ZERO_FRACTION`; without it a PHP `float` is a `number`, like `Rating::$average` ([What `json_encode` writes](https://github.com/bidirekt/php-sdk#what-json_encode-writes)). A union of schema classes declares the key of each member in `union`.

## Tags

Tags say the same in `/** */` docblocks, for code that can't use attributes or prefers docblocks. A tag names a schema by its name in the contract:

```php
/** @bidirekt schema */
final class Pet
{
    /** @bidirekt field type=float description="In kilograms" */
    public float $weight;
}

/** @bidirekt schema */
final class NewPet
{
    /** @bidirekt field */
    public string $name;
}

final class PetController
{
    /**
     * @bidirekt rest provides GET /pets
     * @bidirekt response 200 Pet[]
     */
    public function index(Request $request, Response $response): Response
    {
        // ...
    }

    /**
     * @bidirekt rest provides GET /pets/*
     * @bidirekt response 200 Pet
     * @bidirekt response 404
     */
    public function show(
        Request $request,
        Response $response,
        array $args,
    ): Response {
        // ...
    }

    /**
     * @bidirekt rest provides POST /pets
     * @bidirekt request NewPet
     * @bidirekt response 201 Pet
     * @bidirekt response 400
     */
    public function create(Request $request, Response $response): Response
    {
        // ...
    }
}
```

A list body is `Pet[]` in a tag, and a `@bidirekt request` with no schema writes `request: ~`. A service can mix both forms, but never on the same handler, schema or field: `generate` stops. The [Quickstart](https://github.com/bidirekt/php-sdk#quickstart) of the README writes this example with tags too, and [Schemas without a class](https://github.com/bidirekt/php-sdk#schemas-without-a-class) shows a schema declared on its handler, for a body no class describes.

`#[BidirektProvider]`, `#[BidirektConsumer]`, `@bidirekt provides` and `@bidirekt consumes`, the names before `#[BidirektRestProvider]`, `#[BidirektRestConsumer]`, `@bidirekt rest provides` and `@bidirekt rest consumes`, stop `generate` with the new name: `#[BidirektProvider] was renamed, so it is not read: write #[BidirektRestProvider] and use Bidirekt\PhpSdk\BidirektRestProvider`, and `unknown tag "@bidirekt provides": write "@bidirekt rest provides"`.

Other tools that read docblocks must leave `@bidirekt` alone. `doctrine/annotations` (Symfony annotation routing, Doctrine ORM 2) stops at `@bidirekt` as an annotation that "was never imported": ignore it with `\Doctrine\Common\Annotations\AnnotationReader::addGlobalIgnoredName('bidirekt');` in your app's bootstrap. PHP-CS-Fixer's `phpdoc_to_comment` rule, in the `@Symfony` and `@PhpCsFixer` sets and in Pint's `symfony` preset, turns a `/** */` above a statement like `$app->get(...)` into a `/* */`, which `generate` does not read: keep it with `'phpdoc_to_comment' => ['ignored_tags' => ['bidirekt']]` in `.php-cs-fixer.php`, or the same rule config in `pint.json`.

## GraphQL

For GraphQL, the SDK writes what a service consumes, and the graph of a subgraph. A provider publishes the GraphQL schema its application already has, which the SDK does not write ([GraphQL: Resources](https://bidirekt.com/docs/graphql/resources.md#the-provider-publishes-its-schema)).

`#[BidirektGraphqlConsumer]` on a method declares a field the service calls: the `provider`, `query` or `mutation` with the field's name, the schema of the `arguments` it sends and the shape it `returns`. `#[BidirektGraphqlField]` takes the place of `#[BidirektField]` on a field that needs an option of GraphQL: `scalar`, a custom scalar that replaces the field's type, or `arguments`, the arguments the call passes to that field. Here `petstore_web` calls the GraphQL API of `petstore_api`:

```php
<?php
// src/PetstoreClient.php

namespace App;

use Bidirekt\PhpSdk\BidirektField;
use Bidirekt\PhpSdk\BidirektGraphqlConsumer;
use Bidirekt\PhpSdk\BidirektGraphqlField;
use Bidirekt\PhpSdk\BidirektSchema;

#[BidirektSchema]
final class PetArgs
{
    #[BidirektField]
    public string $id;
}

#[BidirektSchema]
final class ReviewsArgs
{
    #[BidirektField]
    public int $first;
}

#[BidirektSchema]
final class Review
{
    #[BidirektField]
    public int $stars;
}

#[BidirektSchema]
final class Pet
{
    #[BidirektField]
    public string $name;

    #[BidirektGraphqlField(scalar: 'DateTime', optional: true)]
    public \DateTimeImmutable $bornAt;

    /** @var list<Review> */
    #[BidirektGraphqlField(arguments: ReviewsArgs::class)]
    public array $reviews;
}

final class PetstoreClient
{
    #[BidirektGraphqlConsumer(provider: 'petstore_api', query: 'pets', returns: [Pet::class])]
    #[BidirektGraphqlConsumer(provider: 'petstore_api', query: 'petCount', returns: 'integer')]
    public function pets(): void {}

    #[BidirektGraphqlConsumer(
        provider: 'petstore_api',
        query: 'pet',
        arguments: PetArgs::class,
        returns: ['nullable' => Pet::class, 'name' => 'MaybePet'],
    )]
    public function pet(string $id): void {}
}
```

`generate` writes the calls under `consumes.petstore_api.graphql`. A `returns` that is not a schema returned as it is becomes a schema of its own: `[Pet::class]` is `PetList`, `'integer'` is `Integer`, and `['nullable' => Pet::class, 'name' => 'MaybePet']` is `MaybePet`:

```yaml
# Generated by bidirekt/php-sdk. Do not edit.
consumes:
  petstore_api:
    graphql:
      query:
        pet:
          arguments: PetArgs
          returns: MaybePet
        petCount:
          returns: Integer
        pets:
          returns: PetList
schemas:
  Integer:
    type: integer
  MaybePet:
    ref: Pet
    nullable: true
  Pet:
    type: object
    properties:
      name:
        type: string
      bornAt:
        type: scalar
        name: DateTime
        optional: true
      reviews:
        type: array
        items:
          ref: Review
        arguments: ReviewsArgs
  PetArgs:
    type: object
    properties:
      id:
        type: string
  PetList:
    type: array
    items:
      ref: Pet
  Review:
    type: object
    properties:
      stars:
        type: integer
  ReviewsArgs:
    type: object
    properties:
      first:
        type: integer
```

With tags, `@bidirekt graphql consumes <provider> query|mutation <name>` goes above the handler, followed by `@bidirekt arguments <schema>` and `@bidirekt returns <type>`, and `@bidirekt graphql field` takes the place of `@bidirekt field`:

```php
/** @bidirekt schema */
final class Pet
{
    /** @bidirekt field */
    public string $name;

    /** @bidirekt graphql field scalar=DateTime optional=true */
    public \DateTimeImmutable $bornAt;
}

final class PetstoreClient
{
    /**
     * @bidirekt graphql consumes petstore_api query pet
     * @bidirekt arguments PetArgs
     * @bidirekt returns Pet? as MaybePet
     */
    public function pet(string $id): void {}
}
```

A call that reads the type name declares a field `__typename` typed with a PHP enum whose values are the type names it reads. Like any enum, it becomes a `ref` to an `enum` schema:

```php
enum SearchHitTypename: string
{
    case Pet = 'Pet';
    case Toy = 'Toy';
}

#[BidirektSchema]
final class SearchHit
{
    #[BidirektField]
    public SearchHitTypename $__typename;
}

final class SearchClient
{
    #[BidirektGraphqlConsumer(provider: 'petstore_api', query: 'search', returns: [SearchHit::class])]
    public function search(): void {}
}
```

```yaml
schemas:
  SearchHit:
    type: object
    properties:
      __typename:
        ref: SearchHitTypename
  SearchHitList:
    type: array
    items:
      ref: SearchHit
  SearchHitTypename:
    type: enum
    members: ["Pet", "Toy"]
```

When `petstore_api` renames `Pet` to `Animal` in its union `SearchResult`, the call breaks: the report is in [Reading the type name](https://bidirekt.com/docs/graphql/resources.md#reading-the-type-name). A call that reads any type name types `$__typename` as `string`, written as `type: string`, which never breaks on a rename.

Two handlers may call the same field of the same provider with different `returns` or `arguments`. `generate` writes both, as lists in alphabetical order without repeats, with `~` first in `arguments` for a handler that sends none; a field with one schema is still written as a plain name ([Several schemas for one field](https://bidirekt.com/docs/graphql/resources.md#several-schemas-for-one-field)). For example, two handlers of `pets` that return `[PetCard::class]` and `[PetName::class]` write:

```yaml
        pets:
          returns: [PetCardList, PetNameList]
```

A call whose query names a GraphQL type declares that name ([Type names](https://bidirekt.com/docs/graphql/resources.md#type-names)). `scalar:` takes the built-in names too: `#[BidirektGraphqlField(scalar: 'ID')]` writes `{type: scalar, name: ID}`. On an input object, an output object or an enum, the option `graphqlType` of `#[BidirektSchema]`, or of the `@bidirekt schema` tag, writes `name` on its schema: `#[BidirektSchema(graphqlType: 'PetFilter')]` writes `name: PetFilter`.

`provider` may name a federated graph, and the calls are then checked against the graph its subgraphs compose ([Graphs](https://bidirekt.com/docs/graphql/graphs.md#consuming-a-graph)). A subgraph declares its graph with `#[BidirektGraph('petstore_graph')]` on a class, or `@bidirekt graph petstore_graph` above any element, and `generate` writes it as `provides.graphql.graph`. Every form `returns` takes, lists, nullables, primitives, scalars, enums and unions, is in [GraphQL returns](https://github.com/bidirekt/php-sdk#graphql-returns) of the README.

## Describe what the code does

The contract describes what the code does, not the type the code declares ([Describe what the code does](https://bidirekt.com/docs/contracts/the-contract-file.md#describe-what-the-code-does)). With the SDK, the PHP type is where each field starts, and the field's options apply the rule: a declared `type`, `optional` or `nullable` wins over the PHP type.

In the example, `nickname` declares `optional: true` because the code leaves it unset when the pet has none, and `json_encode` leaves an unset typed property out. A `?string $name` whose database column allows `null`, but which the service always fills, declares `#[BidirektField(nullable: false)]`, and a `\DateTimeImmutable` the body carries as a string declares `#[BidirektField(type: 'string')]`.

## From code to deploy

`contracts/generated.yaml` is the service's contract file: a service adopts the SDK as a whole, with every resource and schema it provides or consumes annotated in its code. A subgraph's contract is that file together with its GraphQL schema ([GraphQL](#graphql)). Regenerate the file whenever an annotation or an annotated type changes, and commit it with the code. Then the flow is the same as with a hand-written file:

```
$ vendor/bin/php-sdk generate
$ bidirekt validate
$ bidirekt validate --participant petstore_php --environment production
$ bidirekt publish --participant petstore_php --version 1.4.0
$ bidirekt can-i-deploy petstore_php --version 1.4.0 --environment production
$ bidirekt record-deployment petstore_php --version 1.4.0 --environment production
```

Without file arguments, [`validate`](https://bidirekt.com/docs/ship/validate.md) and [`publish`](https://bidirekt.com/docs/ship/publish.md) read the `contracts/` folder of the current directory ([The contracts folder](https://bidirekt.com/docs/ship/publish.md#the-contracts-folder)). `validate` without `--participant` and `--environment` checks only the file; with them, it also compares the file with what is deployed in that environment. Deploy between `can-i-deploy` and `record-deployment`. In CI, `vendor/bin/php-sdk generate --check` fails the build when the committed file is out of date. `generate --project <folder>` reads another project and writes to its `contracts/` folder, and `--out <file>` writes to another file.

A subgraph, a service that declares its graph with `#[BidirektGraph]` or `@bidirekt graph`, passes its GraphQL schema next to the folder, as `bidirekt validate contracts/ src/schema.graphql` and `bidirekt publish contracts/ src/schema.graphql --participant petstore_reviews --version 2.0.0`: `contracts/` alone fails with `graph "petstore_graph" without a GraphQL schema`.

The broker reads every file of one publish as one contract ([Several files](https://bidirekt.com/docs/contracts/the-contract-file.md#several-files)), but the SDK cannot see a hand-written file: a tag or an attribute cannot name a schema declared only there, and a schema or a provided resource declared both in the code and in a hand-written file is rejected at publish as declared twice. A consumed resource declared in both is merged, like the fragments of one consumer ([Several files](https://bidirekt.com/docs/contracts/the-contract-file.md#several-files)). To adopt the SDK, annotate every resource and schema the service provides or consumes, generate, check that the new file declares what the old files did, and delete the old files.

When [`can-i-deploy`](https://bidirekt.com/docs/ship/can-i-deploy.md) reports a break, fix the annotation or the type in the code and generate again. Never edit `contracts/generated.yaml`: the next `generate` writes over it.

A type the contract cannot hold, such as `mixed` or a `\DateTimeImmutable` without a declared `type`, stops `generate` with the file and the line, and nothing is written. The [`generate` command](https://github.com/bidirekt/php-sdk#the-generate-command) and the [Reference](https://github.com/bidirekt/php-sdk#reference) of the README list every argument, tag, type and error.
