create-psr11-container

Generate a PSR-11 compliant container implementation for PHP 8.4. Implement ContainerInterface with service resolution, support for autowiring, and exception handling, and include unit tests.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "create-psr11-container" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-3fc401086dfe1e2e16b7db6425360e14e275b8fa6520afc6c12b4e0f3a095ab0. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Generate a PSR-11 compliant container implementation for PHP 8.4. Implement ContainerInterface with service resolution, support for autowiring, and exception handling, and include unit tests.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Generates PSR-11 Container implementation for PHP 8.4. Creates ContainerInterface with service resolution, autowiring support, and exceptions. Includes unit tests.
Audience
Building lightweight DI container Creating service locator Simple service resolution needs Testing with mock containers
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: create-psr11-container
description: Generates PSR-11 Container implementation for PHP 8.4. Creates ContainerInterface with service resolution, autowiring support, and exceptions. Includes unit tests.

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

Component Description Location
Container Container implementation src/Infrastructure/Container/
Exceptions PSR-11 exceptions src/Infrastructure/Container/
Unit Tests PHPUnit tests tests/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

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value78/100

Highlights

  • 提供 PSR-11 标准容器实现生成,满足 PHP 开发者依赖注入需求
  • 包含简单容器和自动装配容器两种实现,覆盖不同使用场景
  • 附带完整的单元测试模板,提升代码质量
Trigger Precision85/100

Highlights

  • description 明确描述核心功能:生成 PSR-11 容器实现
  • 关键词覆盖全面:服务解析、自动装配、异常处理、单元测试
Structure and Standards92/100

Highlights

  • 文档结构完整,包含概述、使用场景、生成组件、模板、示例、依赖要求
  • 提供多个代码模板(简单容器、自动装配容器、异常类、单元测试)
  • 包含端到端使用示例,便于用户理解和应用
Execution Reliability88/100

Highlights

  • 代码模板符合 PSR-11 标准,实现完整
  • 自动装配容器包含反射机制,支持依赖自动解析
  • 异常处理完善,覆盖服务未找到、无法实例化等场景
  • 单元测试覆盖主要功能点,确保可靠性
Evidence Verifiability (mean of the first four)86/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.