check-singleton-antipattern

Detect the singleton antipattern in PHP code, identifying global-state issues caused by static instances, hidden dependencies, tight coupling, and testability problems.

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 "check-singleton-antipattern" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-28bb122fbab8d307164a7aa804bc248d31098a2844c1158806ca0fe26fb7d161. 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

Detect the singleton antipattern in PHP code, identifying global-state issues caused by static instances, hidden dependencies, tight coupling, and testability problems.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Detects Singleton anti-pattern in PHP code. Identifies global state via static instances, hidden dependencies, tight coupling, and testability issues.
Inputs and outputs
```markdown
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: check-singleton-antipattern
description: Detects Singleton anti-pattern in PHP code. Identifies global state via static instances, hidden dependencies, tight coupling, and testability issues.

Singleton Anti-Pattern Detection

Analyze PHP code for Singleton anti-pattern usage that introduces global state and tight coupling.

Detection Patterns

1. Classic Singleton Implementation

// ANTIPATTERN: Static instance with private constructor
final class DatabaseConnection
{
    private static ?self $instance = null;

    private function __construct(
        private readonly PDO $pdo,
    ) {}

    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self(new PDO('mysql:host=localhost'));
        }
        return self::$instance;
    }
}

// Usage creates hidden dependency
class UserRepository
{
    public function find(int $id): User
    {
        $db = DatabaseConnection::getInstance(); // Hidden dependency!
        return $db->query("SELECT * FROM users WHERE id = ?", [$id]);
    }
}

2. Registry / Service Locator (Singleton Variant)

// ANTIPATTERN: Global registry acting as singleton container
final class Registry
{
    private static array $services = [];

    public static function set(string $key, mixed $value): void
    {
        self::$services[$key] = $value;
    }

    public static function get(string $key): mixed
    {
        return self::$services[$key] ?? throw new RuntimeException("Not found: $key");
    }
}

// Usage hides ALL dependencies
class OrderService
{
    public function create(array $data): Order
    {
        $repo = Registry::get('orderRepository'); // Hidden dependency
        $mailer = Registry::get('mailer');         // Hidden dependency
    }
}

3. Static State Accumulation

// ANTIPATTERN: Mutable static state
class EventBus
{
    private static array $listeners = [];

    public static function subscribe(string $event, callable $listener): void
    {
        self::$listeners[$event][] = $listener;
    }

    public static function dispatch(string $event, mixed $data): void
    {
        foreach (self::$listeners[$event] ?? [] as $listener) {
            $listener($data);
        }
    }
}
// Problem: State leaks between tests, no way to reset

4. Late Static Binding Singleton

// ANTIPATTERN: Singleton via late static binding
abstract class BaseSingleton
{
    protected static array $instances = [];

    public static function getInstance(): static
    {
        $class = static::class;
        if (!isset(static::$instances[$class])) {
            static::$instances[$class] = new static();
        }
        return static::$instances[$class];
    }
}

5. Framework Anti-Patterns

// ANTIPATTERN: Laravel Facade misuse (global state access)
class OrderController
{
    public function store(): Response
    {
        Cache::put('key', 'value');    // Static singleton access
        Log::info('Order created');     // Static singleton access
        Event::dispatch(new Created()); // Static singleton access
        // All dependencies hidden — not in constructor
    }
}

// CORRECT: Inject dependencies
final readonly class OrderController
{
    public function __construct(
        private CacheInterface $cache,
        private LoggerInterface $logger,
        private EventDispatcherInterface $events,
    ) {}
}

Grep Patterns

# Classic singleton
Grep: "static.*\$instance|getInstance\(\)|private function __construct" --glob "**/*.php"

# Static service access
Grep: "static function get|static function getInstance|static::getInstance" --glob "**/*.php"

# Global state via static arrays
Grep: "private static array|protected static array" --glob "**/*.php"

# Registry / Service Locator
Grep: "Registry::get|ServiceLocator::get|Container::get" --glob "**/*.php"

# Mutable static properties
Grep: "static \$[a-z]+ =" --glob "**/Domain/**/*.php"

Severity Classification

Pattern Severity
Singleton in Domain layer 🔴 Critical
Service Locator pattern 🔴 Critical
Static mutable state 🟠 Major
Framework facade in Domain 🟠 Major
Static helper/utility 🟡 Minor

Correct Alternatives

Use Dependency Injection

// CORRECT: DI container manages lifecycle
final readonly class UserRepository
{
    public function __construct(
        private PDO $connection, // Injected, not global
    ) {}

    public function find(UserId $id): User
    {
        // Use injected dependency
        $stmt = $this->connection->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$id->value()]);
        return $this->hydrate($stmt->fetch());
    }
}

// Container configuration (single instance if needed)
$container->singleton(PDO::class, fn () => new PDO($dsn));

Use Factory for Complex Creation

// CORRECT: Factory instead of Singleton
final readonly class ConnectionFactory
{
    public function __construct(
        private DatabaseConfig $config,
    ) {}

    public function create(): PDO
    {
        return new PDO(
            $this->config->dsn(),
            $this->config->username(),
            $this->config->password(),
        );
    }
}

Output Format

### Singleton Anti-Pattern: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`

**Issue:**
[Description of the singleton/global state problem]

**Impact:**
- Hidden dependency — not visible in constructor
- Tight coupling — cannot substitute in tests
- Global state — shared mutable state between tests/requests

**Code:**
```php
// Current singleton usage

Fix:

// Refactored with dependency injection

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value82/100

Highlights

  • 提供 PHP 单例反模式检测能力,面向开发者代码质量提升
  • 覆盖多种常见反模式场景(经典单例、注册表、静态状态等)
  • 具有明确的目标用户群体(PHP 开发者)和实用价值
Trigger Precision92/100

Highlights

  • description 明确描述功能为检测 PHP 代码中的单例反模式
  • 触发词精准覆盖静态实例、隐藏依赖、紧耦合等核心特征
  • 边界清晰,不易与其他代码检测工具混淆
Structure and Standards95/100

Highlights

  • 文档结构清晰,包含检测模式、Grep 模式、严重性分类、正确替代方案和输出格式
  • 提供完整代码示例和修复建议,便于用户理解与执行
  • frontmatter 完整,单文件内容组织良好
Execution Reliability88/100

Highlights

  • 提供具体 Grep 命令用于检测,参数明确且可执行
  • 覆盖主要异常场景并给出严重性分级(Critical/Major/Minor)
  • 提供正确的依赖注入替代方案,指导用户修复问题
Evidence Verifiability (mean of the first four)89/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.