Skip to content
acc-create-psr11-container logo

PSR-11 Container Generator

acc-create-psr11-container

Generates PSR-11 Container implementation for PHP 8.5. Creates ContainerInterface with service resolution, autowiring support, and exceptions. Includes unit tests.

SKILL.md

Full skill instructions

PSR-11 Container Generator

Overview

Generates PSR-11 compliant dependency injection container implementations.

When to Use

  • Building lightweight DI container
  • Creating service locator
  • Simple service resolution needs
  • Testing with mock containers

Generated Components

ComponentDescriptionLocation
ContainerContainer implementationsrc/​Infrastructure/​Container/
ExceptionsPSR-11 exceptionssrc/​Infrastructure/​Container/
Unit TestsPHPUnit teststests/​Unit/​Infrastructure/​Container/

Template: Simple Container

<?php

declare(strict_types=1);

namespace App\Infrastructure\Container;

use Closure;
use Psr\Container\ContainerInterface;

final class Container implements ContainerInterface
{
    /​** @var array<string, mixed> */
    private array $services = [];

    /​** @var array<string, Closure> */
    private array $factories = [];

    public function get(string $id): mixed
    {
        if (isset($this->services[$id])) {
            return $this->services[$id];
        }

        if (isset($this->factories[$id])) {
            $this->services[$id] = ($this->factories[$id])($this);

            return $this->services[$id];
        }

        throw new NotFoundException("Service not found: {$id}");
    }

    public function has(string $id): bool
    {
        return isset($this->services[$id]) || isset($this->factories[$id]);
    }

    public function set(string $id, mixed $service): void
    {
        $this->services[$id] = $service;
    }

    public function factory(string $id, Closure $factory): void
    {
        $this->factories[$id] = $factory;
    }
}

Template: Autowiring Container

<?php

declare(strict_types=1);

namespace App\Infrastructure\Container;

use Closure;
use Psr\Container\ContainerInterface;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionParameter;

final class AutowiringContainer implements ContainerInterface
{
    /​** @var array<string, mixed> */
    private array $services = [];

    /​** @var array<string, Closure> */
    private array $factories = [];

    /​** @var array<string, string> */
    private array $aliases = [];

    public function get(string $id): mixed
    {
        $id = $this->resolveAlias($id);

        if (isset($this->services[$id])) {
            return $this->services[$id];
        }

        if (isset($this->factories[$id])) {
            $this->services[$id] = ($this->factories[$id])($this);

            return $this->services[$id];
        }

        if (class_exists($id)) {
            $this->services[$id] = $this->autowire($id);

            return $this->services[$id];
        }

        throw new NotFoundException("Service not found: {$id}");
    }

    public function has(string $id): bool
    {
        $id = $this->resolveAlias($id);

        return isset($this->services[$id])
            || isset($this->factories[$id])
            || class_exists($id);
    }

    public function set(string $id, mixed $service): void
    {
        $this->services[$id] = $service;
    }

    public function factory(string $id, Closure $factory): void
    {
        $this->factories[$id] = $factory;
    }

    public function alias(string $alias, string $id): void
    {
        $this->aliases[$alias] = $id;
    }

    private function resolveAlias(string $id): string
    {
        return $this->aliases[$id] ?? $id;
    }

    private function autowire(string $class): object
    {
        $reflection = new ReflectionClass($class);

        if (!$reflection->isInstantiable()) {
            throw new ContainerException("Cannot instantiate: {$class}");
        }

        $constructor = $reflection->getConstructor();

        if ($constructor === null) {
            return new $class();
        }

        $parameters = $constructor->getParameters();
        $dependencies = array_map(
            fn(ReflectionParameter $param) => $this->resolveDependency($param),
            $parameters,
        );

        return new $class(...$dependencies);
    }

    private function resolveDependency(ReflectionParameter $parameter): mixed
    {
        $type = $parameter->getType();

        if ($type === null) {
            if ($parameter->isDefaultValueAvailable()) {
                return $parameter->getDefaultValue();
            }

            throw new ContainerException(
                "Cannot resolve parameter: {$parameter->getName()}",
            );
        }

        if (!$type instanceof ReflectionNamedType || $type->isBuiltin()) {
            if ($parameter->isDefaultValueAvailable()) {
                return $parameter->getDefaultValue();
            }

            throw new ContainerException(
                "Cannot resolve builtin type: {$parameter->getName()}",
            );
        }

        return $this->get($type->getName());
    }
}

Template: Exceptions

<?php

declare(strict_types=1);

namespace App\Infrastructure\Container;

use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

final class ContainerException extends Exception implements ContainerExceptionInterface
{
}

final class NotFoundException extends Exception implements NotFoundExceptionInterface
{
}

Template: Unit Test

<?php

declare(strict_types=1);

namespace App\Tests\Unit\Infrastructure\Container;

use App\Infrastructure\Container\AutowiringContainer;
use App\Infrastructure\Container\NotFoundException;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

#[Group('unit')]
#[CoversClass(AutowiringContainer::class)]
final class AutowiringContainerTest extends TestCase
{
    private AutowiringContainer $container;

    protected function setUp(): void
    {
        $this->container = new AutowiringContainer();
    }

    #[Test]
    public function it_resolves_registered_service(): void
    {
        $service = new \stdClass();
        $this->container->set('service', $service);

        self::assertSame($service, $this->container->get('service'));
    }

    #[Test]
    public function it_resolves_factory(): void
    {
        $this->container->factory('service', fn() => new \stdClass());

        $service1 = $this->container->get('service');
        $service2 = $this->container->get('service');

        self::assertSame($service1, $service2);
    }

    #[Test]
    public function it_autowires_class(): void
    {
        $service = $this->container->get(SimpleService::class);

        self::assertInstanceOf(SimpleService::class, $service);
    }

    #[Test]
    public function it_throws_not_found_for_unknown_service(): void
    {
        $this->expectException(NotFoundException::class);

        $this->container->get('unknown');
    }

    #[Test]
    public function it_resolves_aliases(): void
    {
        $this->container->set('concrete', new \stdClass());
        $this->container->alias('alias', 'concrete');

        self::assertSame(
            $this->container->get('concrete'),
            $this->container->get('alias'),
        );
    }
}

class SimpleService
{
}

Usage Example

<?php

use App\Infrastructure\Container\AutowiringContainer;

$container = new AutowiringContainer();

// Register services
$container->set('config', ['db' => 'mysql://localhost/​app']);

// Register factories
$container->factory(LoggerInterface::class, fn($c) => new FileLogger('/​var/​log/​app.log'));

// Register aliases (interface to implementation)
$container->alias(UserRepositoryInterface::class, DoctrineUserRepository::class);

// Resolve services
$logger = $container->get(LoggerInterface::class);
$repository = $container->get(UserRepositoryInterface::class);
$handler = $container->get(CreateUserHandler::class); // Autowired

Requirements

{
    "require": {
        "psr/​container": "^2.0"
    }
}

See Also

  • references/​templates.md - Additional container patterns
  • references/​examples.md - Integration examples

More skills from diegosouzapw

accessibility logo
diegosouzapw/awesome-omni-skill

accessibility

Accessibility guidelines for VS Code features — covers accessibility help dialogs, accessible views, verbosity settings, accessibility signals, ARIA alerts/status announcements, keyboard navigation, and ARIA labels/roles. Applies to both new interactive UI surfaces and updates to existing feature...

62 1
View
mermaid-diagrams logo
diegosouzapw/awesome-omni-skill

mermaid-diagrams

Mermaid diagram creation for flowcharts, sequences, ERDs, and more. Generate diagrams from text in markdown files. Use for documentation, architecture diagrams, and visual representations. Triggers on mermaid, flowchart, sequence diagram, ERD, entity relationship, gantt chart, pie chart, class di...

62 1
View
tauri2-react-rust logo
diegosouzapw/awesome-omni-skill

tauri2-react-rust

Guides development of cross-platform desktop apps with Tauri 2, TypeScript, React, and Rust. Use when building Tauri apps, implementing IPC, designing Rust backend or TypeScript/React frontend, when researching or cloning a website (open site, snapshot elements), when verifying local dev or built...

62 1
View
fp-ts-errors logo
diegosouzapw/awesome-omni-skill

fp-ts-errors

Handle errors as values using fp-ts Either and TaskEither for cleaner, more predictable TypeScript code. Use when implementing error handling patterns with fp-ts.

62 0
View
ring:pre-dev-research logo
diegosouzapw/awesome-omni-skill

ring:pre-dev-research

Gate 0 research phase for pre-dev workflow. Dispatches 3 parallel research agents to gather codebase patterns, external best practices, and framework documentation BEFORE creating PRD/TRD. Outputs research.md with file:line references.

62 0
View
create-assistant logo
diegosouzapw/awesome-omni-skill

create-assistant

Create and configure Vapi voice AI assistants with models, voices, transcribers, tools, hooks, and advanced settings. Use when building voice agents, phone bots, customer support assistants, or any conversational AI that handles phone or web calls.

62 0
View
codex-headless logo
diegosouzapw/awesome-omni-skill

codex-headless

Delegiere Aufgaben an OpenAI Codex CLI im Headless-Mode. Nutzt ChatGPT Subscription (KEIN API Key). Nur Workspace-Zugriff, KEIN System-Zugriff. Auto-Accept mit --full-auto. Web-Recherche mit --search.

62 0
View
social-media-scheduler logo
diegosouzapw/awesome-omni-skill

social-media-scheduler

Generate a full week of social media content for any topic. Outputs platform-optimized posts for Twitter/X, LinkedIn, and Instagram with hashtags and posting times.

62 0
View
Data Privacy Compliance logo
diegosouzapw/awesome-omni-skill

Data Privacy Compliance

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, da...

62 0
View
triple-review logo
diegosouzapw/awesome-omni-skill

triple-review

Reviews a task using the TRIPLE protocol, as the review agent.

62 0
View
Tech Stack & Architecture Decision logo
diegosouzapw/awesome-omni-skill

Tech Stack & Architecture Decision

Define and document the technology stack and architecture decisions for a project. Use when the user needs to choose a tech stack, make architecture decisions, define infrastructure choices, or document technology selections. Triggers on requests like "define the tech stack", "choose technologies...

62 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View