Skip to content

michtio/craftcms-claude-skills / skills/craft-php-guidelines

craft-php-guidelines

Verified

Craft CMS 5 PHP coding standards and conventions. ALWAYS load when writing, editing, reviewing, or discussing any PHP in a Craft plugin or module — even small edits. Also when running ECS, PHPStan, or scaffolding with ddev craft make. Covers: PHPDoc blocks (@author, @since, @throws chains), section headers (=========), class organization, naming conventions (services, queue jobs, records, events, enums), defineRules() and validation, beforePrepare() and addSelect(), MemoizableArray, DateTimeHelper vs Carbon, strict_types/declare(strict_types=1), short nullable notation (?string), typed properties, void returns, control flow (early returns, match over switch), CP Twig template conventions, form macros, translations (Craft::t), ECS/PHPStan config, scaffolding commands, and the verification checklist.

references/templates-and-patterns.md

View on GitHub
# CP Templates, Validation, Translations, and File Headers

## CP Twig Templates

Indent with 4 spaces. Spaces inside delimiters: `{{ value }}`, `{% tag %}`, `{# comment #}`.

### File Naming

- `_underscore` prefix = partial (not directly accessible via URL). Use for includes, layouts, and components.
- No underscore = route entry point or publicly accessible template.
- Lowercase with hyphens for directories: `plugin-store/`, `entry-types/`.
- camelCase for form macro names: `textField`, `lightswitchField`.

### Template Directory Structure

```
templates/
├── _components/         # Reusable UI components (sidebars, cards)
├── _includes/           # Shared partials (forms, pagination)
├── _layouts/            # Base layouts for CP pages
├── settings/            # Settings pages (route-accessible)
│   ├── _edit.twig       # Edit partial
│   └── index.twig       # Index entry point
```

### Control Structures

```twig
{% if condition %}
    Something
{% endif %}

{% for item in items %}
    {{ item.title }}
{% endfor %}
```

### Form Macros

Import Craft's form helpers and use the object syntax:

```twig
{% import '_includes/forms.twig' as forms %}

{{ forms.textField({
    label: "Name"|t('app'),
    id: 'name',
    name: 'name',
    value: entity.name,
    errors: entity.getErrors('name'),
    required: true,
}) }}
```

### Defaults and Null Coalescing

Use `??` for safe defaults in templates:

```twig
{% set readOnly = readOnly ?? false %}
{% set title = title ?? 'Untitled'|t('app') %}
```

### Output Safety

Never use `|raw` on user-provided or admin-provided content rendered inside `<style>` or `<script>` tags — even admin-entered values are XSS vectors if an admin account is compromised. For CSS values, sanitize or whitelist. For HTML content, use `|purify` (Craft's HTML Purifier filter). Reserve `|raw` for trusted, hardcoded content or content that has already been sanitized.

### Whitespace Control

Use `{%-` and `-%}` to trim surrounding whitespace in low-level components:

```twig
{%- set class = class ?? 'default' -%}
```

## Validation

Use `defineRules()` with array notation:

```php
protected function defineRules(): array
{
    $rules = parent::defineRules();
    $rules[] = [['name', 'handle'], 'required'];
    $rules[] = [['handle'], UniqueValidator::class, 'targetClass' => MyEntityRecord::class];
    $rules[] = [['batchSize'], 'integer', 'min' => 1, 'max' => 500];
    $rules[] = [['apiUrl'], 'url'];
    return $rules;
}
```

Always call `parent::defineRules()` first to inherit base validation. Use Craft's built-in validators (`HandleValidator`, `UniqueValidator`, `DateTimeValidator`) before writing custom ones.

### Inline Validators

Use the **string method name** form for inline validators. Do not use `[$this, 'method']` callable arrays or inline closures:

```php
// Correct — matches craft\models\Section, craft\models\EntryType
$rules[] = [['siteSettings'], 'validateSiteSettings'];
$rules[] = [['previewTargets'], 'validatePreviewTargets'];

// Wrong — Craft core does not use this form
$rules[] = [['siteSettings'], [$this, '_validateSiteSettings']];

// Wrong — inline closures make rules unreadable, prevent reuse
$rules[] = [['siteSettings'], function ($attribute) { ... }];
```

The validator method is **public, no underscore prefix**. Yii's validator dispatcher invokes it by name on the model instance, making it part of the public API surface:

```php
public function validateSiteSettings(): void
{
    if (empty($this->siteSettings)) {
        $this->addError('siteSettings', Craft::t('my-plugin', 'At least one site is required.'));
    }
}
```

The `when` callable in validator rules follows the same pattern — public method, no underscore:

```php
$rules[] = [['maxRows'], 'integer', 'min' => 1, 'when' => [$this, 'hasMaxRows']];

public function hasMaxRows(): bool
{
    return $this->maxRows !== null;
}
```

## Translations

Always use the plugin handle as the translation category:

```php
Craft::t('pluginhandle', 'Some translatable text')
```

```twig
{{ 'Some translatable text'|t('pluginhandle') }}
```

In CP templates, translate labels inline with the `|t()` filter:

```twig
{{ forms.textField({
    label: "Field Label"|t('pluginhandle'),
    instructions: "Help text for this field."|t('pluginhandle'),
}) }}
```

Never hardcode user-facing strings. All CP labels, messages, and descriptions must go through `Craft::t()` or the `|t()` Twig filter.

## File Header

Every PHP file starts with:

```php
<?php
/**
 * <Plugin Name> plugin for Craft CMS
 *
 * <Plugin description>.
 *
 * @link      <Author URL>
 * @copyright Copyright (c) <Year> <Author Name>
 */

namespace vendor\pluginhandle\path\to;
```
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall