Skip to content

PHP ​

This guide explains how to use Skir in a PHP project. Targets PHP 8.4 and higher, with declare(strict_types=1); in every generated file and full static type-checking support via PHPStan at level 8.

Set up ​

In your skir.yml file, add the following snippet under generators:

yaml
- mod: skir-php-gen
  outDir: ./skirout
  config: {}
  # Or with a custom namespace prefix:
  # outDir: ./src/skirout
  # config:
  #   namespacePrefix: "MyApp\\"

The generated PHP code has a runtime dependency on the gepheum/skir-client Composer package, and generates skirout/autoload.php to autoload all generated classes. Add both in your composer.json:

json
{
  "require": {
    "php": ">=8.4",
    "gepheum/skir-client": "^0.1"
  },
  "autoload": {
    "files": ["skirout/autoload.php"]
  }
}

For more information, see this PHP project example.

Generated code guide ​

The examples below are for the code generated from this .skir file.

Referring to generated symbols ​

Each .skir file path/to/my_module.skir generates skirout/path/to/my_module.php in namespace <namespacePrefix>Skirout\Path\To\MyModule:

php
<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use Skirout\User\Consts;
use Skirout\User\SubscriptionStatus;
use Skirout\User\SubscriptionStatus_Kind;
use Skirout\User\SubscriptionStatus_Trial;
use Skirout\User\User;
use Skirout\User\User_Pet;
use Skirout\User\UserRegistry;

Nested records use _ in their PHP class name (for example, User.Pet becomes User_Pet, and SubscriptionStatus.Trial becomes SubscriptionStatus_Trial).

Structs ​

For every struct S in the .skir file, Skir generates a deeply immutable final class S with public readonly properties.

php
// By default, calling `new User(...)` requires ALL fields of the struct to be
// specified. Omitting a field or passing the wrong type fails both PHPStan
// static analysis and PHP's strict runtime type checks.

$john = new User(
    userId: 42,
    name: 'John Doe',
    quote: 'Coffee is just a socially acceptable form of rage.',
    pets: [
        new User_Pet(
            name: 'Dumbo',
            heightInMeters: 1.0,
            picture: '🐘',
        ),
    ],
    subscriptionStatus: SubscriptionStatus::caseFree(),
    // foo: 'bar',
    // ^ Static & runtime error: 'foo' is not a field of User
);

assert($john->name === 'John Doe');

// With 'User::partial(...)', you don't need to specify all the fields of the
// struct. Omitted fields are initialized to their default values.
$jane = User::partial(
    userId: 43,
    name: 'Jane Doe',
);

assert($jane->quote === '');
assert($jane->pets === []);

// 'User::default()' returns a singleton holding the default instance of User.
assert(User::default() == User::partial());

Creating modified copies with replace(...) ​

Because generated structs are immutable, every struct provides a type-safe replace(...) method that returns a new instance with the specified fields updated and all other fields preserved:

php
$evilJane = $jane->replace(
    name: 'Evil Jane',
    quote: 'I am Evil Jane.',
);

assert($evilJane->userId === 43);
assert($evilJane->name === 'Evil Jane');
assert($evilJane->quote === 'I am Evil Jane.');

Enums ​

The definition of the SubscriptionStatus enum in the .skir file is:

skir
enum SubscriptionStatus {
  free;
  trial: Trial;
  premium;

  struct Trial {
    start_time: timestamp;
  }
}

Creating enum values ​

php
use SkirClient\Timestamp;

$johnStatus = SubscriptionStatus::caseFree();
$janeStatus = SubscriptionStatus::casePremium();
$jolyStatus = SubscriptionStatus::caseUnknown();

// Pass the wrapped value to case*(...) for wrapper variants.
$trialStart = Timestamp::fromUnixSeconds(1_744_974_198);
$roniStatus = SubscriptionStatus::caseTrial(
    new SubscriptionStatus_Trial(
        startTime: $trialStart,
    ),
);

// If the wrapped value is a struct, you can use create*(...) instead of
// case*(new Struct(...)).
assert(
    $roniStatus == SubscriptionStatus::createTrial(
        startTime: $trialStart,
    ),
);

Conditions on enums and exhaustive match ​

Every Skir enum Foo generates a native PHP backed enum Foo_Kind: string (Unknown plus a case for each variant such as Free and Trial). Switching on $status->kind with PHP's match expression gives you compile-time exhaustiveness checking in PHPStan (and throws \UnhandledMatchError at runtime if a case is ever omitted):

php
// Check individual variants with is*() and unwrap payloads with as*():
assert($johnStatus->isFree());
assert($jolyStatus->isUnknown());
assert($roniStatus->isTrial());
assert($roniStatus->asTrial()->startTime->equals($trialStart));

// Exhaustive match on `$status->kind` (checked statically by PHPStan):
function getSubscriptionInfoText(SubscriptionStatus $status): string
{
    return match ($status->kind) {
        SubscriptionStatus_Kind::Unknown => 'Unknown subscription status',
        SubscriptionStatus_Kind::Free => 'Free user',
        SubscriptionStatus_Kind::Premium => 'Premium user',
        SubscriptionStatus_Kind::Trial => 'On trial since ' . $status->asTrial()->startTime,
    };
}

Serialization ​

Every struct and enum class provides a static serializer() method returning a \SkirClient\Serializer<self>.

php
$serializer = User::serializer();

// Serialize '$john' to dense JSON (a decoded PHP array/scalar value).
$johnDenseJson = $serializer->toJson($john);
assert(is_array($johnDenseJson));

// toJsonCode returns a JSON string.
$johnDenseJsonCode = $serializer->toJsonCode($john);
assert(str_starts_with($johnDenseJsonCode, '['));

// Serialize '$john' to readable JSON.
echo $serializer->toJsonCode($john, readable: true) . "\n";

// Serialize '$john' to compact binary format (returns a \SkirClient\ByteString).
$johnBytes = $serializer->toBytes($john);

Deserialization ​

php
// Use fromJson, fromJsonCode, and fromBytes to deserialize.
assert($john == $serializer->fromJson($johnDenseJson));
assert($john == $serializer->fromJsonCode($johnDenseJsonCode));
assert($john == $serializer->fromJsonCode($serializer->toJsonCode($john, readable: true)));
assert($john == $serializer->fromBytes($johnBytes));

Primitive and composite serializers ​

php
use SkirClient\ByteString;
use SkirClient\Serializers;
use SkirClient\Timestamp;

assert(Serializers::bool()->toJson(true) === 1);
assert(Serializers::int32()->toJson(3) === 3);
assert(Serializers::int64()->toJson(9_223_372_036_854_775_807) === '9223372036854775807');
// Unsigned 64-bit `hash64` values are represented as decimal strings in PHP
// so values above PHP_INT_MAX (up to 18446744073709551615) never overflow.
assert(Serializers::hash64()->toJson('18446744073709551615') === '18446744073709551615');
assert(Serializers::timestamp()->toJson(Timestamp::fromUnixSeconds(1_743_682_787)) === 1_743_682_787_000);
assert(abs(Serializers::float32()->toJson(3.14) - 3.14) < 1e-5);
assert(Serializers::float64()->toJson(3.14) === 3.14);
assert(Serializers::string()->toJson('Foo') === 'Foo');
assert(Serializers::bytes()->toJson(ByteString::fromBytes("\x01\x02\x03")) === 'AQID');

assert(Serializers::optional(Serializers::string())->toJson('foo') === 'foo');
assert(Serializers::optional(Serializers::string())->toJson(null) === null);
assert(Serializers::array(Serializers::bool())->toJson([true, false]) === [1, 0]);

Keyed arrays ​

php
$userRegistry = new UserRegistry(users: [$john, $jane, $evilJane]);

// searchUsers() returns the user with the given key (specified in the .skir
// file). In this example, the key is the user id.
// The first lookup runs in O(N) time, and the following lookups run in O(1)
// time.
assert($userRegistry->searchUsers(42) === $john);
assert($userRegistry->searchUsers(100) === null);

// If multiple elements have the same key, the search method returns the last
// one. Duplicates are allowed but generally discouraged.
assert($userRegistry->searchUsers(43) === $evilJane);

Constants ​

Each const declared in a .skir file (e.g. const TARZAN: User = ...) is generated as a static method on the module's Consts class:

php
$tarzan = Consts::tarzan();
assert($tarzan->name === 'Tarzan');
echo $tarzan . "\n";

SkirRPC services ​

Starting a SkirRPC service on an HTTP server - full example here.

Sending RPCs to a SkirRPC service - full example here.

Starting a SkirRPC service ​

\SkirClient\Service integrates with any PHP web framework or runtime (Laravel, Symfony, Slim, RoadRunner, FrankenPHP, or PHP's built-in server):

php
use SkirClient\Service;
use Skirout\Service\GetUserRequest;
use Skirout\Service\GetUserResponse;
use Skirout\Service\Methods;

/** @var Service<array<string, mixed>> $service */
$service = new Service();
$service->addMethod(
    Methods::getUser(),
    static function (GetUserRequest $req, array $reqMeta): GetUserResponse {
        // Return response
        return new GetUserResponse(user: null);
    },
);

// In your HTTP controller / handler:
$rawResponse = $service->handleRequest($requestBody, $_SERVER);
http_response_code($rawResponse->statusCode);
header('Content-Type: ' . $rawResponse->contentType);
echo $rawResponse->data;

Sending RPCs with \SkirClient\ServiceClient ​

php
use SkirClient\ServiceClient;
use Skirout\Service\GetUserRequest;
use Skirout\Service\Methods;

$client = new ServiceClient('http://localhost:8787/myapi');
$response = $client->invokeRemote(
    Methods::getUser(),
    new GetUserRequest(userId: 123),
    ['Authorization' => 'Bearer token'],
);

Reflection ​

Reflection allows you to inspect a Skir type at runtime:

php
use SkirClient\TypeDescriptor;

$userTypeDescriptor = User::serializer()->typeDescriptor();

echo $userTypeDescriptor->asJsonCode() . "\n";

// A TypeDescriptor can be serialized and deserialized.
assert(
    $userTypeDescriptor == TypeDescriptor::fromJsonCode(
        $userTypeDescriptor->asJsonCode(),
    ),
);