Token导航 LogoToken导航

Agent Skill · 研究检索

php-ecosystem(PHP ecosystem 搜索)

php-ecosystem 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

php-ecosystem 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 5,488。

总安装 25,780周安装 771GitHub Stars 67下载 8,639核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:php-ecosystem(PHP ecosystem 搜索)
来源仓库:https://github.com/takeokunn/nixos-configuration
仓库路径:skills/php-ecosystem
安装命令:
npx skills add https://github.com/takeokunn/nixos-configuration --skill 'PHP Ecosystem'
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/takeokunn/nixos-configuration --skill 'PHP Ecosystem'

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于查找 PHP 生态工具链与依赖管理资料。适合在 Codex、Claude、Cursor、Gemini CLI 中检索包管理器用法。可通过 npx 命令从 nixos-configuration 仓库安装。建议结合 composer 与 PEAR 使用场景区分。注意依赖版本锁定与供应链安全。

php-ecosystem 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/php-ecosystem

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/takeokunn/nixos-configuration --skill 'PHP Eco…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

php-ecosystem 怎么安装?

在终端执行 npx skills add https://github.com/takeokunn/nixos-configuration --skill 'PHP Ecosystem'。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

php-ecosystem 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

php-ecosystem 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

php-ecosystem 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

php-ecosystem 用的人多吗?

公开数据是累计安装 25,780 次,近一周安装 771 次,下载 8,639 次,GitHub 67 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

php-ecosystem 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
php-ecosystem

PHP ecosystem 搜索 · 本页

25,78067需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

<php_version> <version_mapping> PHP version-specific feature availability Property hooks (get/set) Asymmetric visibility (public private(set)) #[Deprecated] attribute Lazy objects new MyClass()->method() without parentheses array_find(), array_find_key(), array_any(), array_all() mb_trim(), mb_ltrim(), mb_rtrim() Typed class constants json_validate() function Randomizer::getFloat() and nextFloat() Deep cloning of readonly properties Override attribute Granular DateTime exceptions Readonly classes DNF types (Disjunctive Normal Form) null, false, true as standalone types Constants in traits Deprecate dynamic properties Enums (backed and unit) Readonly properties Fibers Intersection types never return type First-class callable syntax New in initializers Named arguments Attributes Constructor property promotion Union types Match expression Nullsafe operator mixed type </version_mapping>

<recommended_config> php.ini recommended settings for development error_reporting = E_ALL display_errors = On log_errors = On opcache.enable = 1 opcache.validate_timestamps = 1 </recommended_config> </php_version>

<type_system> <union_types> Multiple types for parameter or return function process(string|int $value): string|null {return is_string($value)? $value: (string) $value;} </union_types>

<intersection_types> Value must satisfy all types (PHP 8.1+) function process(Countable&Iterator $collection): int {return count($collection);} </intersection_types>

<dnf_types> Combine union and intersection types (PHP 8.2+) function handle((Countable&Iterator)|null $items): void {if ($items === null) {return;} foreach ($items as $item) {// process}} </dnf_types>

        public function label(): string
        {
            return match($this) {
                self::Draft => 'Draft',
                self::Published => 'Published',
                self::Archived => 'Archived',
            };
        }
    }

    // Usage
    $status = Status::from('published');
    $value = $status->value; // 'published'
  </example>
</pattern>

<pattern name="unit-enum">
  <description>Enum without backing value</description>
  <example>
    enum Suit
    {
        case Hearts;
        case Diamonds;
        case Clubs;
        case Spades;

        public function color(): string
        {
            return match($this) {
                self::Hearts, self::Diamonds => 'red',
                self::Clubs, self::Spades => 'black',
            };
        }
    }
  </example>
</pattern>
<pattern name="readonly-class">
  <description>All properties become readonly (PHP 8.2+)</description>
  <example>
    readonly class ValueObject
    {
        public function __construct(
            public string $name,
            public int $value,
        ) {}
    }
  </example>
</pattern>
    class UserController
    {
        #[Route('/users', 'GET')]
        public function index(): array
        {
            return [];
        }
    }

    // Reading attributes via reflection
    $method = new ReflectionMethod(UserController::class, 'index');
    $attributes = $method->getAttributes(Route::class);
    foreach ($attributes as $attribute) {
        $route = $attribute->newInstance();
        echo $route->path; // '/users'
    }
  </example>
</pattern>

<constructor_promotion> Declare and assign properties in constructor (PHP 8.0+) class Product {public function __construct(private string $name, private float $price, private int $quantity = 0,) {}

        public function getName(): string
        {
            return $this->name;
        }
    }
  </example>
</pattern>

</constructor_promotion>

<named_arguments> Pass arguments by name (PHP 8.0+) function createUser(string $name, string $email, bool $active = true,?string $role = null,): User {//...}

    // Usage with named arguments
    $user = createUser(
        email: 'user@example.com',
        name: 'John Doe',
        role: 'admin',
    );
  </example>
  <decision_tree name="when_to_use">
    <question>Are you skipping optional parameters or improving readability?</question>
    <if_yes>Use named arguments</if_yes>
    <if_no>Use positional arguments for simple calls</if_no>
  </decision_tree>
</pattern>

</named_arguments>

<typed_class_constants> Type declarations for class constants (PHP 8.3+) class Config {public const string VERSION = '1.0.0'; public const int MAX_RETRIES = 3; public const array ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];} </typed_class_constants>

<property_hooks> Property hooks for validation and transformation (PHP 8.4+) class User {public string $email {get => $this->email; set {if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {throw new InvalidArgumentException('Invalid email');} $this->email = strtolower($value);}}} <decision_tree name="when_to_use"> Do you need validation or transformation on property access? <if_yes>Use property hooks instead of getters/setters</if_yes> <if_no>Use simple public properties or readonly</if_no> </decision_tree>

<pattern name="virtual-property">
  <description>Computed property without backing storage (PHP 8.4+)</description>
  <example>
    class User
    {
        public string $fullName {
            get => $this->firstName . ' ' . $this->lastName;
        }

        public function __construct(
            public string $firstName,
            public string $lastName,
        ) {}
    }
  </example>
</pattern>

<pattern name="old_vs_modern">
  <description>Migration from getters/setters to property hooks</description>
  <old_way>
    // Before PHP 8.4: Boilerplate getters/setters
    class Product
    {
        private int $price;

        public function getPrice(): int
        {
            return $this->price;
        }

        public function setPrice(int $price): void
        {
            if ($price < 0) {
                throw new InvalidArgumentException('Price cannot be negative');
            }
            $this->price = $price;
        }
    }

    // Usage
    $product->setPrice(100);
    echo $product->getPrice();
  </old_way>
  <modern_way>
    // PHP 8.4+: Property hooks
    class Product
    {
        public int $price {
            set {
                if ($value < 0) {
                    throw new InvalidArgumentException('Price cannot be negative');
                }
                $this->price = $value;
            }
        }
    }

    // Usage - direct property access
    $product->price = 100;
    echo $product->price;
  </modern_way>
</pattern>

</property_hooks>

<asymmetric_visibility> Public read access with private write (PHP 8.4+) class Order {public private(set) string $status = 'pending'; public private(set) DateTimeImmutable $createdAt; public private(set)?DateTimeImmutable $processedAt = null;

        public function __construct()
        {
            $this->createdAt = new DateTimeImmutable();
        }

        public function process(): void
        {
            $this->status = 'processed';
            $this->processedAt = new DateTimeImmutable();
        }
    }

    // Usage
    $order = new Order();
    echo $order->status;       // OK: public read
    $order->status = 'failed'; // Error: private write
  </example>
  <decision_tree name="when_to_use">
    <question>Do you need public read but controlled write access?</question>
    <if_yes>Use asymmetric visibility (public private(set))</if_yes>
    <if_no>Use readonly for immutable or regular visibility for mutable</if_no>
  </decision_tree>
</pattern>

</asymmetric_visibility>

<deprecated_attribute> Mark functions/methods/constants as deprecated (PHP 8.4+) class ApiService {#[Deprecated(message: 'Use fetchV2() instead', since: '2.0.0')] public function fetch(): array {return $this->fetchV2();}

        public function fetchV2(): array
        {
            // New implementation
        }
    }

    // Usage triggers E_USER_DEPRECATED automatically
    $service->fetch();
  </example>
</pattern>

</deprecated_attribute>

<lazy_objects> Create lazy-initialized objects (PHP 8.4+) class ExpensiveService {public function __construct() {// Heavy initialization...}}

    // Create lazy ghost - initializes only when accessed
    $reflector = new ReflectionClass(ExpensiveService::class);
    $service = $reflector->newLazyGhost(
        function (ExpensiveService $instance) {
            // Called when first property/method accessed
            $instance->__construct();
        }
    );

    // $service not initialized yet
    $service->doSomething(); // Triggers initialization
  </example>
  <decision_tree name="when_to_use">
    <question>Do you need to defer expensive object creation?</question>
    <if_yes>Use lazy ghost for same-class or lazy proxy for interface wrapping</if_yes>
    <if_no>Use regular instantiation</if_no>
  </decision_tree>
</pattern>

</lazy_objects> </type_system>

<context7_integration> <library_id>/php/doc-en</library_id> <trust_score>9.4</trust_score>

<usage_pattern> For PHP core documentation, use library ID /php/doc-en Fetch specific topic documentation with get-library-docs </usage_pattern>

<common_queries> PHP attribute syntax and usage Enumeration types and patterns Readonly properties and classes Property hooks syntax (PHP 8.4) </common_queries> </context7_integration>

<psr_standards> Basic coding standards for PHP files Files MUST use only <?php and <?= tags Files MUST use only UTF-8 without BOM Class names MUST be declared in StudlyCaps Class constants MUST be declared in UPPER_CASE Method names MUST be declared in camelCase

  // File: src/Domain/User/Entity/User.php
  namespace App\Domain\User\Entity;

  class User
  {
      // Fully qualified: App\Domain\User\Entity\User
  }
</example>
  class UserService
  {
      public function __construct(
          private LoggerInterface $logger,
      ) {}

      public function create(array $data): User
      {
          $this->logger->info('Creating user', ['email' => $data['email']]);

          try {
              $user = new User($data);
              $this->logger->debug('User created', ['id' => $user->getId()]);
              return $user;
          } catch (\Exception $e) {
              $this->logger->error('Failed to create user', [
                  'exception' => $e,
                  'data' => $data,
              ]);
              throw $e;
          }
      }
  }
</example>
  function handleRequest(ServerRequestInterface $request): ResponseInterface
  {
      $method = $request->getMethod();
      $uri = $request->getUri();
      $body = $request->getParsedBody();
      $query = $request->getQueryParams();

      // PSR-7 messages are immutable
      $response = new Response();
      return $response
          ->withStatus(200)
          ->withHeader('Content-Type', 'application/json');
  }
</example>
  class ServiceLocator
  {
      public function __construct(
          private ContainerInterface $container,
      ) {}

      public function getUserService(): UserService
      {
          return $this->container->get(UserService::class);
      }
  }
</example>
  class AuthMiddleware implements MiddlewareInterface
  {
      public function process(
          ServerRequestInterface $request,
          RequestHandlerInterface $handler
      ): ResponseInterface {
          $token = $request->getHeaderLine('Authorization');

          if (!$this->validateToken($token)) {
              return new Response(401);
          }

          return $handler->handle($request);
      }
  }
</example>
  class JsonResponder
  {
      public function __construct(
          private ResponseFactoryInterface $responseFactory,
          private StreamFactoryInterface $streamFactory,
      ) {}

      public function respond(array $data, int $status = 200): ResponseInterface
      {
          $json = json_encode($data, JSON_THROW_ON_ERROR);
          $body = $this->streamFactory->createStream($json);

          return $this->responseFactory->createResponse($status)
              ->withHeader('Content-Type', 'application/json')
              ->withBody($body);
      }
  }
</example>
  class ApiClient
  {
      public function __construct(
          private ClientInterface $httpClient,
          private RequestFactoryInterface $requestFactory,
      ) {}

      public function get(string $url): array
      {
          $request = $this->requestFactory->createRequest('GET', $url);
          $response = $this->httpClient->sendRequest($request);

          return json_decode(
              $response->getBody()->getContents(),
              true,
              512,
              JSON_THROW_ON_ERROR
          );
      }
  }
</example>

<design_patterns> Immutable objects representing a value readonly class Money {public function __construct(public int $amount, public string $currency,) {if ($amount < 0) {throw new InvalidArgumentException('Amount cannot be negative');}}

      public function add(Money $other): self
      {
          if ($this->currency !== $other->currency) {
              throw new InvalidArgumentException('Currency mismatch');
          }
          return new self($this->amount + $other->amount, $this->currency);
      }

      public function equals(Money $other): bool
      {
          return $this->amount === $other->amount
              && $this->currency === $other->currency;
      }
  }
</example>
  class PdoUserRepository implements UserRepositoryInterface
  {
      public function __construct(
          private PDO $pdo,
      ) {}

      public function find(UserId $id): ?User
      {
          $stmt = $this->pdo->prepare(
              'SELECT * FROM users WHERE id = :id'
          );
          $stmt->execute(['id' => $id->toString()]);
          $row = $stmt->fetch(PDO::FETCH_ASSOC);

          return $row ? $this->hydrate($row) : null;
      }

      public function save(User $user): void
      {
          $stmt = $this->pdo->prepare(
              'INSERT INTO users (id, email, name)
               VALUES (:id, :email, :name)
               ON DUPLICATE KEY UPDATE email = :email, name = :name'
          );
          $stmt->execute([
              'id' => $user->getId()->toString(),
              'email' => $user->getEmail()->toString(),
              'name' => $user->getName(),
          ]);
      }
  }
</example>
<decision_tree name="when_to_use">
  <question>Do you need to abstract persistence details from domain logic?</question>
  <if_yes>Use Repository pattern</if_yes>
  <if_no>Direct database access may be sufficient for simple CRUD</if_no>
</decision_tree>
      public function handle(CreateUserCommand $command): UserId
      {
          $email = new Email($command->email);

          if ($this->userRepository->findByEmail($email) !== null) {
              throw new UserAlreadyExistsException($email);
          }

          $user = User::create(
              UserId::generate(),
              $email,
              $command->name,
              $this->passwordHasher->hash($command->password),
          );

          $this->userRepository->save($user);
          $this->eventDispatcher->dispatch(new UserCreatedEvent($user));

          return $user->getId();
      }
  }
</example>
  // Concrete implementation
  class RedisCache implements CacheInterface
  {
      public function __construct(
          private \Redis $redis,
      ) {}

      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));
      }
  }

  // Service depending on abstraction
  class ProductService
  {
      public function __construct(
          private ProductRepositoryInterface $repository,
          private CacheInterface $cache,
      ) {}
  }
</example>
<pattern name="require-dev">
  <description>Add development dependencies</description>
  <example>
    composer require --dev phpunit/phpunit
    composer require --dev phpstan/phpstan
    composer require --dev friendsofphp/php-cs-fixer
  </example>
</pattern>

<pattern name="version-constraints">
  <description>Specify version requirements</description>
  <example>
    {
        "require": {
            "php": "^8.3",
            "psr/log": "^3.0",
            "guzzlehttp/guzzle": "^7.0"
        },
        "require-dev": {
            "phpunit/phpunit": "^10.0 || ^11.0",
            "phpstan/phpstan": "^1.10"
        }
    }
  </example>
  <note>^ allows minor version updates, ~ allows patch updates only</note>
</pattern>

</package_management>

<package_development> Standard library package structure my-package/ ├── src/ │ └── MyClass.php ├── tests/ │ └── MyClassTest.php ├── composer.json ├── phpunit.xml.dist ├── phpstan.neon ├──.php-cs-fixer.dist.php ├── LICENSE └── README.md

<pattern name="composer-json">
  <description>Complete composer.json for library</description>
  <example>
    {
        "name": "vendor/my-package",
        "description": "My awesome PHP package",
        "type": "library",
        "license": "MIT",
        "authors": [
            {
                "name": "Your Name",
                "email": "you@example.com"
            }
        ],
        "require": {
            "php": "^8.2"
        },
        "require-dev": {
            "phpunit/phpunit": "^11.0",
            "phpstan/phpstan": "^1.10"
        },
        "autoload": {
            "psr-4": {
                "Vendor\\MyPackage\\": "src/"
            }
        },
        "autoload-dev": {
            "psr-4": {
                "Vendor\\MyPackage\\Tests\\": "tests/"
            }
        },
        "scripts": {
            "test": "phpunit",
            "analyse": "phpstan analyse",
            "cs-fix": "php-cs-fixer fix"
        },
        "config": {
            "sort-packages": true
        }
    }
  </example>
</pattern>

<pattern name="scripts">
  <description>Automate common tasks with Composer scripts</description>
  <example>
    {
        "scripts": {
            "test": "phpunit --colors=always",
            "test:coverage": "phpunit --coverage-html coverage",
            "analyse": "phpstan analyse --memory-limit=512M",
            "cs-check": "php-cs-fixer fix --dry-run --diff",
            "cs-fix": "php-cs-fixer fix",
            "ci": [
                "@cs-check",
                "@analyse",
                "@test"
            ]
        }
    }
  </example>
</pattern>

</package_development>

    class CalculatorTest extends TestCase
    {
        private Calculator $calculator;

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

        #[Test]
        public function itAddsNumbers(): void
        {
            $result = $this->calculator->add(2, 3);

            $this->assertSame(5, $result);
        }

        #[Test]
        #[DataProvider('additionProvider')]
        public function itAddsVariousNumbers(int $a, int $b, int $expected): void
        {
            $this->assertSame($expected, $this->calculator->add($a, $b));
        }

        public static function additionProvider(): array
        {
            return [
                'positive numbers' => [1, 2, 3],
                'negative numbers' => [-1, -2, -3],
                'mixed numbers' => [-1, 2, 1],
                'zeros' => [0, 0, 0],
            ];
        }
    }
  </example>
</pattern>

<pattern name="mocking">
  <description>Create test doubles with PHPUnit</description>
  <example>
    use PHPUnit\Framework\TestCase;

    class UserServiceTest extends TestCase
    {
        #[Test]
        public function itCreatesUser(): void
        {
            // Arrange
            $repository = $this->createMock(UserRepositoryInterface::class);
            $repository
                ->expects($this->once())
                ->method('save')
                ->with($this->isInstanceOf(User::class));

            $hasher = $this->createMock(PasswordHasherInterface::class);
            $hasher
                ->method('hash')
                ->willReturn('hashed_password');

            $service = new UserService($repository, $hasher);

            // Act
            $userId = $service->create('test@example.com', 'password');

            // Assert
            $this->assertInstanceOf(UserId::class, $userId);
        }
    }
  </example>
</pattern>

<pattern name="config">
  <description>PHPUnit configuration file</description>
  <example>
    <!-- phpunit.xml.dist -->
    <?xml version="1.0" encoding="UTF-8"?>
    <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
             bootstrap="vendor/autoload.php"
             colors="true"
             cacheDirectory=".phpunit.cache">
        <testsuites>
            <testsuite name="Unit">
                <directory>tests/Unit</directory>
            </testsuite>
            <testsuite name="Integration">
                <directory>tests/Integration</directory>
            </testsuite>
        </testsuites>
        <source>
            <include>
                <directory>src</directory>
            </include>
        </source>
    </phpunit>
  </example>
</pattern>
    beforeEach(function () {
        $this->calculator = new Calculator();
    });

    test('it adds numbers', function () {
        expect($this->calculator->add(2, 3))->toBe(5);
    });

    test('it subtracts numbers', function () {
        expect($this->calculator->subtract(5, 3))->toBe(2);
    });

    it('throws on division by zero', function () {
        $this->calculator->divide(10, 0);
    })->throws(DivisionByZeroError::class);
  </example>
</pattern>

<pattern name="datasets">
  <description>Pest datasets for parameterized tests</description>
  <example>
    dataset('addition', [
        'positive' => [1, 2, 3],
        'negative' => [-1, -2, -3],
        'mixed' => [-1, 2, 1],
    ]);

    test('it adds numbers correctly', function (int $a, int $b, int $expected) {
        expect($this->calculator->add($a, $b))->toBe($expected);
    })->with('addition');
  </example>
</pattern>

<pattern name="expectations">
  <description>Pest expectation API</description>
  <example>
    test('user properties', function () {
        $user = new User('john@example.com', 'John Doe');

        expect($user)
            ->toBeInstanceOf(User::class)
            ->email->toBe('john@example.com')
            ->name->toBe('John Doe')
            ->isActive()->toBeTrue();
    });
  </example>
</pattern>

<static_analysis> PHPStan configuration # phpstan.neon parameters: level: 8 paths: - src - tests excludePaths: - vendor checkMissingIterableValueType: true checkGenericClassInNonGenericObjectType: true reportUnmatchedIgnoredErrors: true

<pattern name="levels">
  <description>PHPStan strictness levels (0-9)</description>
  <levels>
    <level number="0">Basic checks</level>
    <level number="1">Possibly undefined variables</level>
    <level number="2">Unknown methods on $this</level>
    <level number="3">Wrong return types</level>
    <level number="4">Dead code</level>
    <level number="5">Argument types</level>
    <level number="6">Missing type hints</level>
    <level number="7">Partial union types</level>
    <level number="8">No mixed types</level>
    <level number="9">Mixed type operations</level>
    <level number="10">Stricter implicit mixed (PHPStan 2.0+)</level>
  </levels>
  <note>Start at level 5-6 for existing projects, level 9-10 for new projects. Use --level max for highest available.</note>
</pattern>

<pattern name="level-9-10-config">
  <description>Maximum strictness configuration for new projects</description>
  <example>
    # phpstan.neon
    includes:
        - vendor/phpstan/phpstan-strict-rules/rules.neon

    parameters:
        level: 10  # PHPStan 2.0+ (use 9 for PHPStan 1.x)
        paths:
            - src
            - tests
        checkUninitializedProperties: true
        checkBenevolentUnionTypes: true
        reportPossiblyNonexistentGeneralArrayOffset: true
  </example>
  <note>Level 10 treats implicit mixed (missing types) as strictly as explicit mixed. Use phpstan-strict-rules for additional checks like === enforcement.</note>
</pattern>

<pattern name="generics">
  <description>Generic types with PHPStan annotations</description>
  <example>
    /**
     * @template T
     * @param class-string<T> $class
     * @return T
     */
    public function create(string $class): object
    {
        return new $class();
    }

    /**
     * @template T of object
     * @param T $entity
     * @return T
     */
    public function save(object $entity): object
    {
        // persist
        return $entity;
    }
  </example>
</pattern>
<pattern name="annotations">
  <description>Psalm-specific annotations</description>
  <example>
    /**
     * @psalm-immutable
     */
    readonly class ImmutableValue
    {
        public function __construct(
            public string $value,
        ) {}
    }

    /**
     * @psalm-assert-if-true User $user
     */
    function isActiveUser(?User $user): bool
    {
        return $user !== null && $user->isActive();
    }
  </example>
</pattern>

<php_cs_fixer> PHP CS Fixer configuration <?php //.php-cs-fixer.dist.php $finder = PhpCsFixer\Finder::create() ->in(DIR. '/src') ->in(DIR. '/tests');

    return (new PhpCsFixer\Config())
        ->setRules([
            '@PER-CS' => true,
            '@PHP84Migration' => true,
            'strict_types' => true,
            'declare_strict_types' => true,
            'array_syntax' => ['syntax' => 'short'],
            'no_unused_imports' => true,
            'ordered_imports' => ['sort_algorithm' => 'alpha'],
            'trailing_comma_in_multiline' => true,
        ])
        ->setFinder($finder)
        ->setRiskyAllowed(true);
  </example>
</pattern>

</php_cs_fixer>

    return RectorConfig::configure()
        ->withPaths([
            __DIR__ . '/src',
            __DIR__ . '/tests',
        ])
        ->withSets([
            SetList::CODE_QUALITY,
            SetList::DEAD_CODE,
            SetList::TYPE_DECLARATION,
        ])
        ->withPhpSets(php84: true);
  </example>
  <note>LevelSetList (e.g., UP_TO_PHP_84) deprecated since Rector 0.19.2. Use ->withPhpSets() instead.</note>
</pattern>
    $pdo = new PDO($dsn, $username, $password, $options);
  </example>
</pattern>

<pattern name="prepared-statements">
  <description>Secure parameterized queries</description>
  <example>
    // Named parameters
    $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
    $stmt->execute(['email' => $email]);
    $user = $stmt->fetch();

    // Positional parameters
    $stmt = $pdo->prepare('INSERT INTO users (email, name) VALUES (?, ?)');
    $stmt->execute([$email, $name]);
    $id = $pdo->lastInsertId();
  </example>
  <warning>Never concatenate user input into SQL queries</warning>
</pattern>

<pattern name="transactions">
  <description>Database transactions with PDO</description>
  <example>
    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?');
        $stmt->execute([$amount, $fromAccount]);

        $stmt = $pdo->prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?');
        $stmt->execute([$amount, $toAccount]);

        $pdo->commit();
    } catch (\Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
  </example>
</pattern>
    // Preload commonly used classes
    $classesToPreload = [
        App\Domain\User\User::class,
        App\Domain\Order\Order::class,
    ];

    foreach ($classesToPreload as $class) {
        class_exists($class);
    }
  </example>
  <config>
    ; php.ini
    opcache.preload=/path/to/preload.php
    opcache.preload_user=www-data
  </config>
</pattern>

<error_handling> Custom exception hierarchy // Base domain exception abstract class DomainException extends \Exception {}

  // Specific exceptions
  class EntityNotFoundException extends DomainException
  {
      public static function forClass(string $class, string $id): self
      {
          return new self(sprintf('%s with id "%s" not found', $class, $id));
      }
  }

  class ValidationException extends DomainException
  {
      public function __construct(
          string $message,
          public readonly array $errors = [],
      ) {
          parent::__construct($message);
      }
  }

  // Usage
  throw EntityNotFoundException::forClass(User::class, $userId);
</example>
      /** @return self<T, never> */
      public static function ok(mixed $value): self
      {
          return new self(true, $value);
      }

      /** @return self<never, E> */
      public static function error(mixed $error): self
      {
          return new self(false, $error);
      }

      public function isSuccess(): bool { return $this->success; }
      public function isError(): bool { return !$this->success; }
      public function getValue(): mixed { return $this->value; }
  }

  // Usage
  function divide(int $a, int $b): Result
  {
      if ($b === 0) {
          return Result::error('Division by zero');
      }
      return Result::ok($a / $b);
  }
</example>

<array_functions> <php84_functions> Find first element matching predicate (PHP 8.4+) $users = [['id' => 1, 'active' => false], ['id' => 2, 'active' => true], ['id' => 3, 'active' => true],];

    $firstActive = array_find($users, fn($user) => $user['active']);
    // ['id' => 2, 'active' => true]
  </example>
</function>

<function name="array_find_key">
  <description>Find key of first element matching predicate (PHP 8.4+)</description>
  <example>
    $users = [
        'john' => ['active' => false],
        'jane' => ['active' => true],
    ];

    $firstActiveKey = array_find_key($users, fn($user) => $user['active']);
    // 'jane'
  </example>
</function>

<function name="array_any">
  <description>Check if any element matches predicate (PHP 8.4+)</description>
  <example>
    $hasAdmin = array_any($users, fn($u) => $u['role'] === 'admin');
  </example>
</function>

<function name="array_all">
  <description>Check if all elements match predicate (PHP 8.4+)</description>
  <example>
    $allActive = array_all($users, fn($u) => $u['active']);
  </example>
</function>

</php84_functions> </array_functions>

<anti_patterns> Classes that do too much Split into focused single-responsibility classes

  // Good
  $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
  $stmt->execute([$email]);
</example>

<best_practices> Enable strict_types in all PHP files Use prepared statements for all database queries Use PHPStan level 9+ for type safety Use readonly classes for value objects Follow PSR-12 coding style Use enums instead of string/int constants Inject dependencies through constructor Use named arguments for complex function calls Create custom exceptions for domain errors Use attributes for metadata instead of docblock annotations </best_practices>

<error_escalation> Minor coding style issue Auto-fix with PHP CS Fixer PHPStan error or missing type Fix type, verify with static analysis Breaking API change or security issue Stop, present options to user SQL injection or authentication bypass Block operation, require immediate fix </error_escalation>

<related_skills> Symbol-level navigation for class and interface definitions Fetch latest PHP and library documentation Test strategy and coverage patterns PDO patterns and query optimization </related_skills>

平台分布

Codex

35.77%
按下载量换算3,090

Claude

31.53%
按下载量换算2,724

Cursor

19.61%
按下载量换算1,694

Gemini CLI

8.99%
按下载量换算777

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills