Logo Php Type Safety

Php Type Safety

Cộng đồng
peterfox
php-type-safety

PHP type safety patterns using webmozarts/assert for runtime validation combined with PHPDoc annotations for static analysis. Use this skill whenever writing or reviewing PHP code that needs to pass PHPStan or Psalm at strict levels, when adding type assertions to method/function parameters, when typing complex array structures (shapes, maps, lists), when defining reusable type aliases, or when annotating anonymous objects and key/value arrays. Trigger on phrases like "add type assertions", "type this array properly", "make this pass PHPStan", "annotate with PHPDoc", "use webmozarts assert", "type hints for static analysis", "psalm types", or any request to improve type safety in PHP code.

Tổng quan

Nhà phát hànhpeterfox
Kho mãagent-skills
Tên kỹ năngphp-type-safety
Sao
25
Bản fork
0
Tệp đi kèm
3
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 3 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được peterfox công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Php Type Safety trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/peterfox/agent-skills/tree/main/php-type-safety
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/peterfox/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/php-type-safety .claude/skills/php-type-safety
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Php Type Safety trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Php Type Safety ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Php Type Safety không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

PHP Type Safety

Combine runtime assertions (webmozarts/assert) with static analysis annotations (PHPDoc shapes, templates) to write PHP code that is safe at runtime and satisfies PHPStan/Psalm at strict levels. The two approaches are complementary: PHPDoc narrows types for the analyser, assertions enforce them at runtime where PHP's type system cannot.

Setup

bash
composer require webmozart/assert
composer require --dev phpstan/phpstan-webmozart-assert  # PHPStan users only

The PHPStan extension translates Assert::*() calls into type-narrowing expressions so PHPStan refines variable types after each assertion. If you use phpstan/extension-installer it registers automatically; otherwise add it to phpstan.neon:

neon
includes:
    - vendor/phpstan/phpstan-webmozart-assert/extension.neon

Psalm users need no extra plugin — the Assert library ships with @psalm-assert annotations on every method and Psalm reads them natively.

Core workflow

  1. Annotate first — write the PHPDoc shape or type hint so the analyser knows the expected type.
  2. Assert at boundaries — use Assert::*() at the entry point of any method that receives data from outside your control (user input, deserialized data, external APIs, mixed-typed collections).
  3. Avoid redundant assertions — if PHP's native type system or a previous assertion already guarantees the type, a second assertion adds noise.
  4. Define type aliases for shapes used in more than one place.

PHPDoc type annotations

Scalar and object types

Prefer native type hints. Use PHPDoc only when native PHP cannot express the type:

php
/** @param non-empty-string $slug */
public function findBySlug(string $slug): void {}

/** @param positive-int $count */
public function paginate(int $count): void {}

/** @param class-string<Entity> $class */
public function resolve(string $class): object {}

Array shapes — exact structure

Use array shapes for arrays with a known, fixed set of keys:

php
/**
 * @param array{id: int, name: string, email?: string} $user
 * @return array{token: string, expires_at: int}
 */
public function createSession(array $user): array {}

email?: string marks email as optional (may be absent).

Generic arrays — maps and lists

Use generic notation for arrays where all values share a type:

php
/** @param array<string, int> $scores */   // map: string keys, int values
/** @param list<User> $users */             // list: 0-indexed, sequential
/** @param non-empty-list<string> $tags */  // list with at least one item

Use list<T> (not array<int, T>) for sequential integer-indexed arrays — it carries stronger guarantees that PHPStan/Psalm can leverage.

Type aliases — reusable shapes

Define shapes once in the class that owns the data, import elsewhere:

php
/**
 * @phpstan-type UserData array{id: int, name: string, roles: list<string>}
 * @psalm-type    UserData = array{id: int, name: string, roles: list<string>}
 */
class User {}

// In another class:
/**
 * @phpstan-import-type UserData from User
 * @psalm-import-type   UserData from User
 */
class UserRepository {
    /** @return list<UserData> */
    public function findAll(): array {}
}

PHPStan and Psalm have slightly different syntax; include both tags for cross-tool compatibility.

Templates (generics)

php
/**
 * @template T
 * @param list<T> $items
 * @param callable(T): bool $predicate
 * @return list<T>
 */
function filter(array $items, callable $predicate): array {
    return array_values(array_filter($items, $predicate));
}

/**
 * @template T of \Throwable
 * @param class-string<T> $exceptionClass
 * @param callable(): void $fn
 * @throws T
 */
function rethrowAs(string $exceptionClass, callable $fn): void
{
    try {
        $fn();
    } catch (\Throwable $e) {
        throw new $exceptionClass($e->getMessage(), 0, $e);
    }
}

Runtime assertions with webmozarts/assert

Basic usage

php
use Webmozart\Assert\Assert;

public function setAge(int $age): void
{
    Assert::range($age, 0, 150);
    $this->age = $age;
}

public function handle(mixed $payload): void
{
    Assert::isArray($payload);
    Assert::keyExists($payload, 'type');
    Assert::string($payload['type']);
    Assert::inArray($payload['type'], ['create', 'update', 'delete']);
}

Bulk assertions with all* and nullOr*

php
/** @param list<string> $tags */
public function setTags(array $tags): void
{
    Assert::allStringNotEmpty($tags);   // every element is a non-empty string
    $this->tags = $tags;
}

/** @param array<string, int|null> $scores */
public function setScores(array $scores): void
{
    Assert::allNullOrInteger($scores);  // each value is int or null
}

Combining with PHPDoc shapes

Assertions narrow types for runtime; PHPDoc shapes narrow them for the analyser. Use both together at the boundary of untrusted data:

php
/**
 * @phpstan-type RawConfig array{dsn: string, pool: int, timeout?: float}
 * @param array<string, mixed> $raw
 * @return RawConfig
 */
private function validateConfig(array $raw): array
{
    Assert::keyExists($raw, 'dsn');
    Assert::string($raw['dsn']);
    Assert::keyExists($raw, 'pool');
    Assert::positiveInteger($raw['pool']);
    if (isset($raw['timeout'])) {
        Assert::float($raw['timeout']);
    }

    /** @var RawConfig $raw */
    return $raw;
}

The @var cast is a forced assertion — it tells the analyser to treat $raw as RawConfig from that point on. The analyser trusts it; the assertions above are what actually enforce it at runtime.

Legacy inference mode

Use this mode when asked to "infer types", "annotate without changing the API", or improve type visibility in existing code where modifying method signatures would risk breaking callers.

The constraint: add type information only through PHPDoc and internal assertions. Never add or change native PHP type hints (string $name, : int, ?Foo), never alter a method or function signature in any way.

What you may add

AdditionExample
@param / @return PHPDoc on methods/** @param list<int> $ids */
@var on class properties/** @var array<string, User> */
@var on local variables/** @var non-empty-string $slug */
Assert::*() inside method bodiesAfter receiving or unpacking a value
Type alias definitions (@phpstan-type)On the class, not on the signature

What you must not touch

  • Native parameter types (string $x, int $x, ?Foo $x)
  • Native return types (: string, : void, : ?int)
  • Anything else that changes the method or function signature

Inference workflow

  1. Read the method body — trace how each parameter and return value is actually used. Assignment to a typed property, a method call that requires a specific type, a comparison — all give clues.
  2. Check callers — if accessible, read call sites to see what values are passed.
  3. Annotate conservatively — if you cannot determine the type with confidence, use mixed or the broadest type you can prove. Do not guess.
  4. Add assertions where the inferred type is not guaranteed — if callers could pass anything and the body assumes a string, guard it with Assert::string() at the top.
  5. Use @var for local ambiguity — when a variable is assigned from a source the analyser cannot follow (e.g. array_shift, casting, unserialize), annotate inline.

Example

Before — legacy code, no type information:

php
class OrderService
{
    private $repository;
    private $items = [];

    public function add($product, $qty)
    {
        $this->items[] = ['product' => $product, 'qty' => $qty];
    }

    public function total()
    {
        $sum = 0;
        foreach ($this->items as $line) {
            $sum += $line['product']->price * $line['qty'];
        }
        return $sum;
    }
}

After — annotated in inference mode (signatures untouched):

php
/**
 * @phpstan-type LineItem array{product: Product, qty: positive-int}
 */
class OrderService
{
    /** @var ProductRepository */
    private $repository;

    /** @var list<LineItem> */
    private $items = [];

    /**
     * @param Product $product
     * @param positive-int $qty
     */
    public function add($product, $qty)
    {
        Assert::isInstanceOf($product, Product::class);
        Assert::positiveInteger($qty);

        $this->items[] = ['product' => $product, 'qty' => $qty];
    }

    /**
     * @return float
     */
    public function total()
    {
        $sum = 0;
        foreach ($this->items as $line) {
            $sum += $line['product']->price * $line['qty'];
        }
        return $sum;
    }
}

The public API is identical. PHPStan/Psalm now understands the property types, the expected parameter contracts, and the return type — and the assertions catch violations at runtime during development.

Decision rules

  • Do not assert what PHP already enforces. If a parameter has string $name, don't add Assert::string($name).
  • Assert at boundaries, not everywhere. Internal private methods working with already-typed data don't need assertions.
  • Use Assert::isInstanceOf() instead of a cast. It produces a cleaner error than a failed cast and narrows the type for PHPStan/Psalm.
  • Prefer specific assertions over generic ones. Assert::positiveInteger() communicates intent better than Assert::integer() + a manual range check.
  • Open shapes for extensible structures. When a shape may contain extra keys you don't control, Psalm users can use array{known: type, ...}; PHPStan users should document this in the PHPDoc prose or use array<string, mixed>.
  • In inference mode, annotate conservatively. A mixed annotation you can prove is safer than a specific type you cannot. Incorrect PHPDoc is worse than missing PHPDoc — it misleads the analyser and future readers.

Reference files

  • references/assert-methods.md — Full categorised reference for all Assert methods; read when you need a specific assertion or the nullOr/all prefix variants.
  • references/phpdoc-shapes.md — Deep reference for array shapes, list types, conditional types, and cross-tool differences between PHPStan and Psalm; read when annotating complex structures.
  • references/phpstan-extension.md — Installation, configuration, and the exact list of assertions that cause PHPStan type narrowing; read when debugging why PHPStan is not narrowing a type after an assertion, or when verifying the extension is working.

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Php Type Safety làm được gì?

PHP type safety patterns using webmozarts/assert for runtime validation combined with PHPDoc annotations for static analysis. Use this skill whenever writing or reviewing PHP code that needs to pass PHPStan or Psalm at strict levels, when adding type assertions to method/function parameters, when typing complex array structures (shapes, maps, lists), when defining reusable type aliases, or when annotating anonymous objects and key/value arrays. Trigger on phrases like "add type assertions", "type this array properly", "make this pass PHPStan", "annotate with PHPDoc", "use webmozarts assert"...

Vì sao nên dùng Php Type Safety trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Php Type Safety là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Php Type Safety trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/peterfox/agent-skills/tree/main/php-type-safety. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Php Type Safety?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Php Type Safety với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Php Type Safety với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Php Type Safety có miễn phí không?

Có. Kỹ năng này được peterfox phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇