cloud-native-knowledge

云原生知识库。提供将十二要素应用原则应用于 PHP 的具体实现建议、容器优先模式以及面向架构审计的环境配置方案。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "cloud-native-knowledge":https://skillpi.com/zh/skills/deepskill-b017256b94b96be7111bd2911f9f31fd173e892e1ba889d2aee286db67454a13。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

云原生知识库。提供将十二要素应用原则应用于 PHP 的具体实现建议、容器优先模式以及面向架构审计的环境配置方案。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: cloud-native-knowledge
description: Cloud Native knowledge base. Provides 12-Factor App principles with PHP-specific implementations, container-first patterns, and environment configuration for architecture audits.

Cloud Native Knowledge Base

Quick reference for 12-Factor App principles with PHP-specific implementations and container-first patterns.

12-Factor App Overview

┌─────────────────────────────────────────────────────────────────────┐
│                     12-FACTOR APP FLOW                               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐     │
│   │ Codebase │───▶│   Build  │───▶│ Release  │───▶│   Run    │     │
│   │ (Git)    │    │ (Docker) │    │ (Tag)    │    │ (K8s)    │     │
│   └──────────┘    └──────────┘    └──────────┘    └──────────┘     │
│        │                │               │               │           │
│        │                │               │               │           │
│   ┌────▼─────┐    ┌────▼─────┐    ┌────▼─────┐    ┌────▼─────┐    │
│   │ composer │    │  ENV     │    │ Backing  │    │ Stateless│    │
│   │ .lock    │    │ Config   │    │ Services │    │ Processes│    │
│   │ (Deps)   │    │ (No .env │    │ (Redis,  │    │ (PHP-FPM │    │
│   │          │    │  in prod)│    │  DB, MQ) │    │  shared  │    │
│   └──────────┘    └──────────┘    └──────────┘    │  nothing)│    │
│                                                    └──────────┘    │
│                                                                      │
│   ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐     │
│   │ Port     │    │ Concur-  │    │ Dispos-  │    │ Dev/Prod │     │
│   │ Binding  │    │ rency    │    │ ability  │    │ Parity   │     │
│   │ (FPM,   │    │ (FPM     │    │ (Fast    │    │ (Docker  │     │
│   │  Runner) │    │  workers)│    │  start/  │    │  Compose)│     │
│   └──────────┘    └──────────┘    │  stop)   │    └──────────┘     │
│                                    └──────────┘                      │
│   ┌──────────┐    ┌──────────┐                                      │
│   │ Logs     │    │ Admin    │                                      │
│   │ (stderr  │    │ Processes│                                      │
│   │  stream) │    │ (Console │                                      │
│   └──────────┘    │  cmds)   │                                      │
│                    └──────────┘                                      │
└─────────────────────────────────────────────────────────────────────┘

The 12 Factors

# Factor PHP Implementation Anti-Pattern
1 Codebase One Git repo per service Multiple services in one repo (unless monorepo with clear boundaries)
2 Dependencies composer.lock committed, no global installs System-level pecl install without Dockerfile
3 Config $_ENV, getenv(), DotEnv (dev only) Hardcoded DB credentials, config in code
4 Backing services DSN via env vars, adapter pattern Direct new Redis('localhost')
5 Build, release, run Docker multi-stage build composer install in production at runtime
6 Processes Stateless PHP-FPM, shared-nothing $_SESSION file storage, local temp files
7 Port binding PHP built-in server, FrankenPHP, RoadRunner Apache module (mod_php) requiring full server
8 Concurrency PHP-FPM process model, horizontal scaling Single monolithic process
9 Disposability Fast startup, pcntl_signal for SIGTERM Long bootstrap, no graceful shutdown
10 Dev/prod parity Docker Compose matches production SQLite in dev, PostgreSQL in prod
11 Logs Monolog StreamHandler('php://stderr') Writing to /var/log/app.log files
12 Admin processes Symfony Console, artisan, one-off containers SSH into server and run scripts

Factor Details with PHP Examples

Factor 3: Config — Environment Variables

<?php

declare(strict_types=1);

namespace Infrastructure\Config;

final readonly class DatabaseConfig
{
    public readonly string $host;
    public readonly int $port;
    public readonly string $name;
    public readonly string $user;
    public readonly string $password;

    public function __construct()
    {
        $this->host = $this->requireEnv('DB_HOST');
        $this->port = (int) $this->requireEnv('DB_PORT');
        $this->name = $this->requireEnv('DB_NAME');
        $this->user = $this->requireEnv('DB_USER');
        $this->password = $this->requireEnv('DB_PASSWORD');
    }

    public function dsn(): string
    {
        return sprintf(
            'pgsql:host=%s;port=%d;dbname=%s',
            $this->host,
            $this->port,
            $this->name,
        );
    }

    private function requireEnv(string $name): string
    {
        $value = $_ENV[$name] ?? getenv($name);

        if ($value === false || $value === '') {
            throw new \RuntimeException(sprintf(
                'Required environment variable "%s" is not set',
                $name,
            ));
        }

        return (string) $value;
    }
}

Factor 4: Backing Services — Adapter Pattern

<?php

declare(strict_types=1);

namespace Infrastructure\Cache;

final readonly class RedisCacheAdapter implements CacheInterface
{
    private \Redis $redis;

    public function __construct()
    {
        $this->redis = new \Redis();
        $this->redis->connect(
            (string) ($_ENV['REDIS_HOST'] ?? 'localhost'),
            (int) ($_ENV['REDIS_PORT'] ?? 6379),
        );

        $password = $_ENV['REDIS_PASSWORD'] ?? null;
        if ($password !== null && $password !== '') {
            $this->redis->auth($password);
        }
    }

    public function get(string $key): mixed
    {
        $value = $this->redis->get($key);

        return $value !== false ? unserialize($value) : null;
    }

    public function set(string $key, mixed $value, int $ttl = 3600): void
    {
        $this->redis->setex($key, $ttl, serialize($value));
    }

    public function delete(string $key): void
    {
        $this->redis->del($key);
    }
}

Factor 5: Build, Release, Run — Docker Multi-Stage

# Stage 1: Build (install dependencies, compile assets)
FROM php:8.4-cli AS builder

COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /app

COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --prefer-dist --optimize-autoloader

COPY . .
RUN composer dump-autoload --optimize --classmap-authoritative

# Stage 2: Run (minimal production image)
FROM php:8.4-fpm-alpine AS runtime

RUN docker-php-ext-install pdo_pgsql opcache

COPY docker/php/php.ini /usr/local/etc/php/conf.d/app.ini
COPY docker/php/fpm-pool.conf /usr/local/etc/php-fpm.d/www.conf
COPY --from=builder /app /app

WORKDIR /app

EXPOSE 9000
CMD ["php-fpm"]

Factor 9: Disposability — Graceful Shutdown

<?php

declare(strict_types=1);

namespace Infrastructure\Worker;

final class GracefulWorker
{
    private bool $shouldStop = false;

    public function __construct(
        private readonly MessageConsumerInterface $consumer,
    ) {
        pcntl_signal(SIGTERM, [$this, 'handleSignal']);
        pcntl_signal(SIGINT, [$this, 'handleSignal']);
    }

    public function run(): void
    {
        while (!$this->shouldStop) {
            pcntl_signal_dispatch();

            $message = $this->consumer->consume(timeoutMs: 1000);

            if ($message !== null) {
                $this->process($message);
                $this->consumer->acknowledge($message);
            }
        }

        $this->consumer->disconnect();
    }

    public function handleSignal(int $signal): void
    {
        $this->shouldStop = true;
    }

    private function process(Message $message): void
    {
        // Process message — keep this fast and idempotent
    }
}

Factor 11: Logs — Stream to stderr

<?php

declare(strict_types=1);

namespace Infrastructure\Logging;

use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;

final readonly class LoggerFactory
{
    public static function create(string $channel = 'app'): LoggerInterface
    {
        $logger = new Logger($channel);

        // 12-Factor: treat logs as event streams to stderr
        // Container runtime (Docker/K8s) captures and forwards
        $logger->pushHandler(new StreamHandler('php://stderr', Logger::INFO));

        return $logger;
    }
}

Factor 12: Admin Processes — One-Off Containers

<?php

declare(strict_types=1);

namespace Infrastructure\Console;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:migrate', description: 'Run database migrations')]
final class MigrateCommand extends Command
{
    public function __construct(
        private readonly MigrationRunnerInterface $migrationRunner,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln('Running migrations...');

        $applied = $this->migrationRunner->run();

        $output->writeln(sprintf('Applied %d migrations.', $applied));

        return Command::SUCCESS;
    }
}

// Run as one-off container:
// docker run --rm myapp:latest php bin/console app:migrate

PHP Violations Table

Factor Violation Why It Breaks Fix
1 Multiple apps in one repo without clear boundaries Deploy coupling, version entanglement Split repos or use monorepo tooling
2 pecl install at runtime Non-reproducible builds Install extensions in Dockerfile
3 .env file in production Secrets in filesystem, not rotatable Use real env vars or secrets vault
3 define('DB_HOST', 'localhost') Config in code Use $_ENV['DB_HOST']
4 new Redis('10.0.0.5') hardcoded Cannot swap backing service Inject via env var DSN
5 composer install at deploy time Slow, network-dependent, non-reproducible Install at build stage
6 $_SESSION with file handler State tied to instance Redis session handler
6 file_put_contents('/tmp/data.json') State on local disk Redis or object storage
7 Apache mod_php only Cannot self-serve on a port FPM + nginx, or FrankenPHP
8 Single-process Swoole without scaling Cannot scale horizontally FPM workers or multi-process Swoole
9 30s bootstrap, no SIGTERM handler Slow deploys, dropped requests Preloading + signal handling
10 SQLite dev, PostgreSQL prod Behavior differences in queries Docker Compose with PostgreSQL
11 file_put_contents('/var/log/app.log') Logs not collected by runtime Monolog to php://stderr
12 SSH into server to run scripts Not auditable, not reproducible One-off container commands

Container-First PHP Patterns

Health Check Endpoint

<?php

declare(strict_types=1);

namespace Presentation\Api\Action;

final readonly class HealthAction
{
    public function __construct(
        private \PDO $pdo,
        private \Redis $redis,
    ) {}

    public function __invoke(): array
    {
        $checks = [];

        try {
            $this->pdo->query('SELECT 1');
            $checks['database'] = 'ok';
        } catch (\Throwable) {
            $checks['database'] = 'fail';
        }

        try {
            $this->redis->ping();
            $checks['redis'] = 'ok';
        } catch (\Throwable) {
            $checks['redis'] = 'fail';
        }

        $healthy = !in_array('fail', $checks, true);

        return [
            'status' => $healthy ? 'healthy' : 'unhealthy',
            'checks' => $checks,
        ];
    }
}

Readiness vs Liveness

┌─────────────────────────────────────────────────────────────────────┐
│                   CONTAINER PROBES                                    │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   Liveness Probe (/healthz)                                         │
│   • "Is the process alive?"                                         │
│   • Checks: PHP-FPM responds, not deadlocked                       │
│   • Failure: container is RESTARTED                                 │
│   • Keep simple: just return 200                                    │
│                                                                      │
│   Readiness Probe (/readyz)                                         │
│   • "Can this instance serve traffic?"                              │
│   • Checks: DB reachable, Redis reachable, migrations applied      │
│   • Failure: instance removed from load balancer                    │
│   • More comprehensive: verify all backing services                 │
│                                                                      │
│   Startup Probe                                                     │
│   • "Has the app finished bootstrapping?"                           │
│   • Checks: OPcache warmed, preloading done                        │
│   • Failure: container not yet considered for liveness/readiness    │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Detection Patterns

# Factor 3: Config via env vars
Grep: "getenv\(|\\$_ENV\[|env\(" --glob "**/*.php"
Grep: "define\(.*HOST\|define\(.*PASSWORD\|define\(.*SECRET" --glob "**/*.php"
Glob: **/.env
Glob: **/.env.prod

# Factor 4: Backing service configuration
Grep: "REDIS_HOST|REDIS_URL|DATABASE_URL|RABBITMQ_URL" --glob "**/.env*"
Grep: "new Redis\(|new \\\\PDO\(" --glob "**/src/**/*.php"

# Factor 5: Build artifacts
Glob: **/Dockerfile
Grep: "composer install" --glob "**/Dockerfile"
Grep: "multi-stage|AS builder|AS runtime" --glob "**/Dockerfile"

# Factor 6: Stateless violations
Grep: "session\.save_handler.*files|session_start" --glob "**/*.php"
Grep: "file_put_contents|fwrite" --glob "**/src/**/*.php"

# Factor 9: Graceful shutdown
Grep: "pcntl_signal|SIGTERM|SIGINT" --glob "**/*.php"

# Factor 11: Log streaming
Grep: "php://stderr|php://stdout" --glob "**/*.php"
Grep: "StreamHandler|error_log" --glob "**/*.php"
Grep: "file_put_contents.*log|fopen.*log" --glob "**/*.php"

# Factor 12: Admin processes
Grep: "AsCommand|Command::class" --glob "**/*.php"
Glob: **/bin/console
Glob: **/artisan

# Container health checks
Grep: "HEALTHCHECK|healthz|readyz" --glob "**/Dockerfile"
Grep: "health_check|liveness|readiness" --glob "**/docker-compose*.yml"

Quick Reference

12-Factor Compliance Checklist

Factor Check Pass Criteria
Codebase Single repo per deployable git remote -v shows one origin
Dependencies Lock file committed composer.lock in Git
Config No secrets in code Zero define() with credentials
Backing services DSN from env All connections via $_ENV
Build/Release/Run Docker multi-stage Separate build and runtime stages
Processes Stateless No $_SESSION files, no local temp
Port binding Self-contained FPM or embedded server
Concurrency Process model pm = dynamic or static
Disposability Fast start/stop < 5s startup, SIGTERM handler
Dev/prod parity Same services Docker Compose mirrors production
Logs Stream to stderr Monolog php://stderr handler
Admin One-off containers Console commands, no SSH

References

For detailed information, load these reference files:

  • references/twelve-factors.md — Detailed explanation of each factor with PHP code examples, DotEnv setup, Symfony secrets vault, Docker CMD, signal handling, log streaming

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值75/100

亮点

  • 提供云原生十二要素应用原则的 PHP 具体实现,具有明确的工程指导价值
  • 涵盖容器优先模式和架构审计方案,适合开发者、架构师和 DevOps 人员参考
触发精准85/100

待提升项

  • description写错位置 原报告严重程度:轻微

    顶层 frontmatter 中 description 字段为空,实际描述内容位于 skill_body 内部

    改进建议:将 description 内容移至顶层 frontmatter 字段,确保触发系统能正确识别

亮点

  • 触发描述清晰完整,覆盖云原生知识库、十二要素、PHP 实现、容器优先、架构审计等核心功能
结构规范90/100

待提升项

  • 缺少When to Use章节 原报告严重程度:轻微

    文档未明确说明适用场景和使用时机

    改进建议:添加 When to Use 章节,说明何时使用此知识库(如架构设计、代码审查、合规检查等)

  • 文档过长 原报告严重程度:轻微

    SKILL.md 文件约 450 行,超出理想长度

    改进建议:考虑将部分内容移至引用文件,保持主文档简洁

亮点

  • 结构清晰,包含概述、详细实现、违规检查表、检测模式等多个逻辑章节
  • 提供丰富的端到端示例,包括 PHP 代码、Dockerfile 和检测命令
执行可靠88/100

亮点

  • 工具来源明确,使用 PHP、Docker、Monolog、Symfony 等标准组件
  • 代码示例覆盖主要异常处理,如环境变量缺失、连接失败等场景
证据可验 (前四项均值)85/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

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

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 53, 449 行

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。