Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

K8S Resources Laravel Package

dealroadshow/k8s-resources

Laravel package for defining and managing Kubernetes resource manifests (e.g., Deployments, Services, Ingress) in PHP. Helps generate, organize, and deploy K8s YAML from your app with reusable resource classes and configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require dealroadshow/k8s-resources
    

    Add to composer.json if using a monorepo or custom setup.

  2. Basic Usage

    use DealRoadshow\K8sResources\Resource\Pod;
    
    $pod = new Pod();
    $pod->setMetadata(['name' => 'my-pod']);
    $pod->setSpec(['containers' => [['name' => 'nginx', 'image' => 'nginx:latest']]]);
    
    $json = $pod->toArray(); // Convert to Kubernetes API-compatible array
    
  3. Where to Look First

    • Resource Classes: Browse src/Resource/ for pre-defined Kubernetes resources (e.g., Pod, Deployment, Service).
    • Documentation: Check the GitHub README for API structure and examples.
    • Validation: Use $resource->validate() to ensure compliance with Kubernetes schema before deployment.

Implementation Patterns

Common Workflows

  1. Dynamic Resource Creation

    use DealRoadshow\K8sResources\Factory;
    
    $factory = new Factory();
    $deployment = $factory->create('Deployment');
    $deployment->setMetadata(['namespace' => 'default']);
    $deployment->setSpec([
        'replicas' => 3,
        'template' => [
            'spec' => ['containers' => [['image' => 'nginx']]]
        ]
    ]);
    
  2. Patch/Update Operations

    $patch = new Pod();
    $patch->setMetadata(['name' => 'existing-pod']);
    $patch->setSpec(['containers' => [['env' => [['name' => 'ENV_VAR', 'value' => 'new-value']]]]]);
    
    // Use with a Kubernetes client (e.g., `kubernetes-client-php`) to apply patches.
    
  3. Integration with Kubernetes Clients

    use DealRoadshow\K8sResources\Resource\ConfigMap;
    use KubeClient\Client;
    
    $client = new Client();
    $configMap = new ConfigMap();
    $configMap->setData(['config.ini' => '[settings]']);
    $client->resource('ConfigMap')->create($configMap->toArray());
    
  4. Custom Resource Definitions (CRDs) Extend the base Resource class to support custom APIs:

    use DealRoadshow\K8sResources\Resource;
    
    class MyCustomResource extends Resource {
        protected $apiVersion = 'mygroup.example/v1';
        protected $kind = 'MyResource';
    }
    

Best Practices

  • Immutable Objects: Treat resources as immutable after validation. Clone or rebuild for modifications.
  • Namespacing: Always set metadata.namespace for cluster-scoped resources (e.g., Deployment, Service).
  • Labels/Annotations: Use setLabels() and setAnnotations() for resource organization and tooling hooks.
  • Validation: Call validate() before serialization to catch schema errors early.

Gotchas and Tips

Pitfalls

  1. Schema Validation Strictness

    • The package enforces Kubernetes API schema validation. Missing required fields (e.g., metadata.name) will throw exceptions.
    • Fix: Ensure all mandatory fields are set before validation.
  2. Nested Resource Complexity

    • Deeply nested specs (e.g., Deployment.spec.template.spec.containers) can be error-prone to construct manually.
    • Tip: Use helper methods or build a DSL for common patterns:
      $podSpec = (new PodSpec())
          ->addContainer('nginx', 'nginx:latest')
          ->setRestartPolicy('Always');
      
  3. API Version Mismatches

    • Some resources support multiple API versions (e.g., apps/v1 vs. apps/v1beta1).
    • Tip: Explicitly set $apiVersion in custom resources to avoid ambiguity.
  4. Performance with Large Manifests

    • Serializing/deserializing large manifests (e.g., StatefulSet with many volumes) can be slow.
    • Tip: Lazy-load or stream resources for large-scale operations.

Debugging

  • Validation Errors: Use validate() with true to get detailed error messages:
    $errors = $resource->validate(true);
    print_r($errors);
    
  • JSON Serialization: If toArray() fails, check for circular references or unsupported PHP types (e.g., DateTime objects). Use json_encode($resource->toArray(), JSON_PRETTY_PRINT) to inspect.

Extension Points

  1. Custom Validators Override validate() to add domain-specific rules:

    class SecurePod extends Pod {
        public function validate(bool $strict = false): array {
            $errors = parent::validate($strict);
            if (empty($this->getSpec()['securityContext'])) {
                $errors[] = 'securityContext is required for secure pods.';
            }
            return $errors;
        }
    }
    
  2. Serialization Hooks Extend toArray() to transform data before serialization:

    class EncryptedSecret extends Secret {
        public function toArray(): array {
            $data = parent::toArray();
            $data['data'] = array_map('base64_encode', $data['data']);
            return $data;
        }
    }
    
  3. Kubernetes Client Integration Create a wrapper for your preferred client (e.g., kubernetes-client-php, kubectl):

    class K8sClient {
        public function apply(Resource $resource): void {
            $client = new Client();
            $client->resource($resource->getKind())
                    ->inNamespace($resource->getMetadata()['namespace'] ?? 'default')
                    ->createOrUpdate($resource->toArray());
        }
    }
    
  4. Testing Use the package to generate test manifests:

    $testDeployment = (new Deployment())
        ->setMetadata(['name' => 'test-deployment'])
        ->setSpec(['replicas' => 1, 'template' => [...]]);
    $this->assertEquals(['apiVersion' => 'apps/v1', ...], $testDeployment->toArray());
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle