Start hereWhy classes

Start here

Why classes

What goes wrong when manifests are text, what a typed program does instead, the opinions Klass8s is built on, and what they cost.

Most Kubernetes setups follow the same path. A few YAML files, readable and explicit. A second environment, and with it duplication. Then templates (Helm) or patches (Kustomize) to remove the duplication, then helper functions, overlay trees, values-prod-eu.yaml, and a CI step nobody wants to touch.

By then the team maintains a program: it has inputs (the environment, settings), logic (conditions, naming rules, the wiring between resources) and an output (manifests). The question is only whether that program is written in a language with types, functions, tests and an editor that understands it, or in a text-templating dialect that has none of them. Klass8s writes it as a program.

What goes wrong with text

FailureWhy it happensWhat a typed program does
A Service selects nothingthe selector and the pod labels are kept by hand in two placesboth come from one declaration and cannot differ
A renamed Secret breaks five Deploymentsreferences are strings, and search is the only refactoring toolDatabaseSecret::class: the editor renames every reference, and a reference to a class that is not in the build fails the render
Pods keep running stale configurationnothing connects a ConfigMap change to the workloads that read itthe checksum of every ConfigMap and Secret a pod reads is in its template, so a change rolls exactly those pods
nindent 8 where nindent 10 was meantlogic is interleaved with whitespace-significant textthe code builds objects; the serializer writes the indentation
A typo in a field or a valuefound when the API server or a validating client reads the outputa method that does not exist, a wrong type or an enum case that does not exist fails before anything is rendered
Per-environment differences spread over filesoverlays and values files keep one decision in several placesreplicasProd() beside replicas(), in the class it changes
"Don't touch it, it works"changes cannot be tested where they are madean App renders in PHPUnit; assertions run on the output in CI

Behind most of these is one fact: Kubernetes resources are objects with a schema, and templating treats them as text. Klass8s builds the objects, from PHP classes generated from the Kubernetes OpenAPI specification (klass8s/k8schema), and serializes them at the end.

The same thing, side by side

A Helm template for a Deployment, in the shape helm create produces:

{{- if .Values.api.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "app.fullname" . }}-api
  labels:
    {{- include "app.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.api.replicas | default 2 }}
  selector:
    matchLabels:
      {{- include "app.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "app.selectorLabels" . | nindent 8 }}
    spec:
      containers:
        - name: api
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          resources:
            {{- toYaml .Values.api.resources | nindent 12 }}
{{- end }}

Everything that matters here (the name, the labels that must be equal in three places, the resources) is assembled by string inclusion with counted indentation, from a values.yaml whose shape is described only by its documentation, or by a values.schema.json kept by hand.

The class:

src/K8S/Checkout/Manifest/ApiDeployment.phnsrc/K8S/Checkout/Manifest/ApiDeployment.php
namespace App\K8S\Checkout\Manifest;

use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Container\Resources\ContainerResourcesInterface;
use Klass8s\Core\Container\Resources\CPU;
use Klass8s\Core\Container\Resources\Memory;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

class ApiDeployment extends AbstractContainerDeployment
{
    const int PORT = 8080;

    static shortName(): string => 'api';

    image(): Image => Image::fromName('acme/checkout-api')->setTag('1.42.0');

    replicas(): int => 2;

    replicasProd(): int => 6;

    ports(PortsConfigurator $ports): void => $ports->add(self::PORT)->setName('http');

    env(EnvConfigurator $env): void {
        $env->addConfigMapClass(ApiConfigMap::class)
            ->varFromSecretClass('PAYMENTS_TOKEN', PaymentsSecret::class, PaymentsSecret::KEY_TOKEN);
    }

    resources(ContainerResourcesInterface $resources): void {
        $resources->requestCPU(CPU::millicores(250))->requestMemory(Memory::mebibytes(256));
    }
}
<?php

declare(strict_types=1);

namespace App\K8S\Checkout\Manifest;

use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Container\Resources\ContainerResourcesInterface;
use Klass8s\Core\Container\Resources\CPU;
use Klass8s\Core\Container\Resources\Memory;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

class ApiDeployment extends AbstractContainerDeployment
{
    public const int PORT = 8080;

    public static function shortName(): string
    {
        return 'api';
    }

    public function image(): Image
    {
        return Image::fromName('acme/checkout-api')->setTag('1.42.0');
    }

    public function replicas(): int
    {
        return 2;
    }

    public function replicasProd(): int
    {
        return 6;
    }

    public function ports(PortsConfigurator $ports): void
    {
        $ports->add(self::PORT)->setName('http');
    }

    public function env(EnvConfigurator $env): void
    {
        $env->addConfigMapClass(ApiConfigMap::class)
            ->varFromSecretClass('PAYMENTS_TOKEN', PaymentsSecret::class, PaymentsSecret::KEY_TOKEN);
    }

    public function resources(ContainerResourcesInterface $resources): void
    {
        $resources->requestCPU(CPU::millicores(250))->requestMemory(Memory::mebibytes(256));
    }
}

The name, the labels and the selector do not appear in it, and are right in every place they are rendered. Whether a resource exists is a class attribute such as #[EnabledForEnvs('prod')] rather than an if around a block of text, and the resources are typed values that can be compared and computed.

What templating cannot reach

Suppose every pod must run under a ServiceAccount the platform provides, unless its manifest names another. With Helm, every chart must remember to template it. With Kustomize, it is a patch in every overlay. With Klass8s it is one subscriber:

src/EventSubscriber/DefaultServiceAccountSubscriber.phnsrc/EventSubscriber/DefaultServiceAccountSubscriber.php
namespace App\EventSubscriber;

use App\K8S\Platform\Manifest\WorkloadServiceAccount;
use App\K8S\Platform\PlatformApp;
use Klass8s\Bundle\EventListener\AbstractManifestMethodResultSubscriber;
use Klass8s\Core\Pod\PodSpecInterface;
use Klass8s\Event\ProxyableMethodCalledEventInterface;
use Klass8s\Manifest\Reference\ManifestClassReference;

/** Every pod runs under the platform's workload ServiceAccount, unless its manifest names one. */
final class DefaultServiceAccountSubscriber extends AbstractManifestMethodResultSubscriber
{
    protected supports(ProxyableMethodCalledEventInterface $event): bool
        => 'serviceAccount' === $event->methodName() && $event->proxyable() instanceof PodSpecInterface;

    protected afterMethod(ProxyableMethodCalledEventInterface $event): void {
        if (null !== $event->returnedValue()) {
            return; // the manifest chose its own
        }

        $event->setReturnValue(new ManifestClassReference(PlatformApp::NAME, WorkloadServiceAccount::class));
    }
}
<?php

declare(strict_types=1);

namespace App\EventSubscriber;

use App\K8S\Platform\Manifest\WorkloadServiceAccount;
use App\K8S\Platform\PlatformApp;
use Klass8s\Bundle\EventListener\AbstractManifestMethodResultSubscriber;
use Klass8s\Core\Pod\PodSpecInterface;
use Klass8s\Event\ProxyableMethodCalledEventInterface;
use Klass8s\Manifest\Reference\ManifestClassReference;

/** Every pod runs under the platform's workload ServiceAccount, unless its manifest names one. */
final class DefaultServiceAccountSubscriber extends AbstractManifestMethodResultSubscriber
{
    protected function supports(ProxyableMethodCalledEventInterface $event): bool
    {
        return 'serviceAccount' === $event->methodName() && $event->proxyable() instanceof PodSpecInterface;
    }

    protected function afterMethod(ProxyableMethodCalledEventInterface $event): void
    {
        if (null !== $event->returnedValue()) {
            return; // the manifest chose its own
        }

        $event->setReturnValue(new ManifestClassReference(PlatformApp::NAME, WorkloadServiceAccount::class));
    }
}

Templating has no moment at which "every pod spec of the build" exists as something a program can address. Klass8s has one, because rendering is a program that runs: every manifest method call and every generated resource is an event. The framework's own labels, checksums and environment handling are subscribers of the same kind, and can be switched off or replaced. See Events.

The opinions behind it

Producing manifests is an application. It gets what applications get: dependency injection for configuration and shared logic, an event system for rules that cut across everything, a test suite, scaffolding, and refactoring that follows ::class references. The cost is explicit: rendering needs PHP and composer install, as a build step.

Derive, don't repeat. A resource contains a lot of information that follows from other information: its name, its labels, its selector, the names of the resources it refers to. You state each fact once (the App is shop, this manifest's short name is api) and Klass8s derives the rest. Strings that must match across files are how YAML setups decay; Klass8s is built so that such strings do not exist.

Environments are code paths, not file trees. What differs between environments stands next to what it changes: an environment-specific method, a method added in some environments only, a manifest that exists in some environments only. Use it with care: an environment that differs in shape stops proving that the others work. Prefer differences in values (a hostname, a replica count) to differences in what exists. See Environments.

Plain output, and a way out at every level. The output is inert YAML that you can diff, commit, hand to a GitOps controller, or keep if you stop using Klass8s. The configurators cover the common fields; every manifest type also has a configure<Kind>() method that receives the generated Kubernetes object, typed, and custom resources are a class with a spec(). A missing feature is never a reason to fork.

Built against the Kubernetes schema, versioned with Kubernetes. klass8s/k8schema has a release line per Kubernetes minor version, so the version constraint in composer.json states which Kubernetes API a project targets, and upgrading is a constraint change followed by whatever the type checker reports.

Why PHP and Phaenon

Because the question is which language your team already writes. Klass8s is for organisations whose products are PHP, where the developers who write a service can open its k8s/ directory with the same editor, the same completion and the same review process, and change its infrastructure themselves. For such a team, manifests in TypeScript (cdk8s) or Go mean a second toolchain, a second package manager and a second set of reviewers.

Modern PHP holds up its end: strict types, enums, readonly classes, property hooks, attributes. Phaenon goes further, with generics, collection types and a checker that reports what PHPStan reports at its strictest level, and compiles to the PHP you would otherwise write.

If your organisation has no PHP, Klass8s is not your tool; cdk8s fits a TypeScript team better.

Where other tools win

  • Helm is the distribution format for third-party software. Keep installing cert-manager and database operators from their charts; Klass8s renders Helm releases next to your own manifests.
  • Kustomize is right for adjusting YAML you do not own: a namespace, an image and two fields.
  • cdk8s and Pulumi write manifests in general-purpose languages too. Pulumi also deploys and keeps state, which Klass8s deliberately does not.

The comparisons go through each: Helm, Kustomize, cdk8s and Pulumi.

What it costs

  • Rendering needs PHP. Only at build time, but a real requirement; it rules Klass8s out where PHP is not used at all.
  • It is a framework, not a file format. Apps, manifests, configurators and events are concepts to learn. The quick start covers the first three in a few minutes.
  • Indirection has a price. When the YAML is wrong, you debug the program that produced it. Rendering is deterministic, the output marks every document with its file name, and render tests assert on it.
  • A small ecosystem. There are few answers to search for. The codebase is small enough to read, and typed enough that the editor answers many questions.