craft-php-guidelines
Skill90 starsChanged 4 months agoMITView on GitHub
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, and when running ECS, PHPStan, or ddev craft make. Covers PHPDoc blocks (@author, @since, @throws chains), section headers (=========), class organization, naming (services, jobs, records, events, enums), defineRules(), beforePrepare() and addSelect(), MemoizableArray, DateTimeHelper vs Carbon, declare(strict_types=1), ?string nullables, early returns, CP Twig templates, form macros, Craft::t, ECS/PHPStan config, and the verification checklist.
In this repository18 other files it gives its agents.
- docs/agents.mdAGENTS.md
- project-template/CLAUDE.mdCLAUDE.md
- reference/CLAUDE.mdCLAUDE.md
- craft-cloudSkill
- craftcmsSkill
- craft-content-modelingSkill
- craft-fortrabbitSkill
- craft-garnishSkill
- craft-gated-buildSkill
- craft-mcpSkill
- craft-pestSkill
- craft-plugin-releaseSkill
- craft-pluginsSkill
- craft-project-setupSkill
- craft-siteSkill
- craft-twig-guidelinesSkill
- ddevSkill
- servdSkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 1 is distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 31
When unsure about a convention, WebFetch the coding guidelines page for the authoritative answer.
- Distinctive: line 35
Read the relevant reference file(s) for your task:
- Very specific: line 57
Always scaffold with ddev craft make <type> --with-docblocks, then customize.
- Very specific: line 74
Only include sections that have content.
- Very specific: line 82
Always specify void return types.
- Very specific: line 105
Copy style: no em-dashes (—) or en-dashes (–) in user-facing copy (Craft::t() strings, labels, CP notices, console output, README, docs).
- Very specific: line 118
No em-dashes (—) or en-dashes (–) in user-facing copy (Craft::t() strings, labels, CP notices, README, docs)
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Craft CMS 5 PHP Guidelines
Craft Version of This Project
!sh ${CLAUDE_SKILL_DIR}/scripts/craft-version.sh
If no Craft version line appears above, establish the version before any version-specific advice: craftcms/cms in composer.lock for a site, the lowest version the craftcms/cms constraint in composer.json allows for a plugin, or ask. Then check it against the version tags in this skill ([5.10+], [changed 5.12], [seomatic 5.1+]).
Complete PHP coding standards and conventions for Craft CMS 5 plugin and module development. These extend Craft's official coding guidelines with project-specific conventions.
Core principles: PHPDocs on everything — classes, methods, and properties — regardless of type hints. No declare(strict_types=1) in plugin source files (matching Craft core convention).
Companion Skills — Always Load Together
craftcms— Architecture patterns, element lifecycle, controllers, events, migrations. Required for any Craft plugin or module development.ddev— All commands run through DDEV. Required for running ECS, PHPStan, scaffolding, and tests.
Documentation
- Official coding guidelines: https://craftcms.com/docs/5.x/extend/coding-guidelines.html
- Class reference: https://docs.craftcms.com/api/v5/
- Generator reference: https://craftcms.com/docs/5.x/extend/generator.html
When unsure about a convention, WebFetch the coding guidelines page for the authoritative answer.
Reference Files
Read the relevant reference file(s) for your task:
| Task | Read | ~Tokens |
Writing PHPDocs, @author, @since, @throws, @var, @param, type references; console controller docblocks as craft help text | references/phpdoc-standards.md | ~1,150 |
| Class structure, section headers, ordering, shared constants, enums, control flow, comments, whitespace | references/class-organization.md | ~2,050 |
| Naming classes, methods, properties, files, services, events, migrations; quick-reference table; kebab-case permission handles and their constants | references/naming-conventions.md | ~1,500 |
| CP Twig templates, form macros, translations, copy style (no em-dashes), file headers, validation | references/templates-and-patterns.md | ~1,350 |
DateTimeHelper vs Carbon, parsing DB datetimes, App::env()/App::parseEnv(), UrlHelper::absoluteUrl() [5.12.2+], doesEnvVarExist() [5.11+], DB conventions, Db::isSafeOrderBy() [5.12+], component registration scope | references/dates-env-database.md | ~1,250 |
ECS, PHPStan (Craft::$app narrowing, magic property access), scaffolding commands, composer hygiene for plugin repos, commit messages | references/tooling.md | ~2,100 |
| Authorization parity across CP / console / GraphQL / queue surfaces, self-referential guards, one shared gate | references/authorization-parity.md | ~2,900 |
Critical Rules
- PHPDocs on everything: classes, methods, properties. No exceptions.
@throwschains: document every exception including uncaught from called methods.@authorand@sinceat the bottom of class/method docblocks, after a blank line.@authorgoes on classes and methods, never on properties. (Craft core puts@authorat the class level only; method-level@authoris this project's house convention. Don't "fix" it.)- Section headers with
// =========================================================================on every class. (Craft core itself uses dash separators —// ----— with functional/domain labels like// Statusesor// Events. The=====separators and visibility labels below are a deliberate house convention for consistency across this project's plugins, not core style.) declare(strict_types=1)is NOT used in plugin source files — Craft's internal type coercion depends on PHP's default weak typing mode. Only standalone config files likeecs.phpuse it.- Private methods/properties prefixed with underscore, with meaningful names:
_registerCpUrlRules(),$_items,$_sections(never$_instances). addSelect()convention inbeforePrepare()— additive across extensions, prevents column conflicts.DateTimeHelperin elements/queries,Carbonin services — never mix them in the same class.- Always scaffold with
ddev craft make <type> --with-docblocks, then customize. ddev composer check-csandddev composer phpstanmust pass before every commit.
Section Header Order
// Traits
// Const Properties
// Static Properties
// Public Properties
// Protected Properties
// Private Properties
// Public Methods
// Protected Methods
// Private MethodsOnly include sections that have content. Blank line after the separator, before the first item. Full example: references/class-organization.md.
PHP Standards
- Minimum PHP 8.2 (Craft CMS 5 requirement).
- PSR-12 baseline with Craft modifications (trailing commas, constant visibility).
craftcms/ecswithSetList::CRAFT_CMS_4preset (covers both Craft 4 and 5).- Short nullable notation:
?stringnotstring|null. - Always specify
voidreturn types. - Typed properties everywhere. No untyped public properties.
- Strict comparison always:
$foo === null,in_array($x, $y, true). - Casts over functions:
(int)$foonotintval($foo). - Control flow: happy path last with early returns, no
else,matchoverswitchfor value-mapping, curly brackets always, compound conditions split into nestedifs, named arguments at 3+ parameters. Seereferences/class-organization.md.
Common Pitfalls
- Records use the same class name as models (namespace distinguishes). Alias when importing both:
use ...\records\MyEntity as MyEntityRecord;. - Queue jobs have no "Job" suffix —
ResaveElements, notResaveElementsJob. Element actions likewise (Delete,SetStatus). - Forget
parent::defineRules()and you lose all inherited validation. - Using
[$this, '_validateFoo']callable arrays or inline closures indefineRules()— Craft core uses string method names:[['attr'], 'validateAttr']. The validator method is public, no underscore — Yii invokes it by name. - Parsing a raw DB datetime with
strtotime()ornew DateTime(): the column is naive UTC and the process timezone issystem.timeZone. UseDateTimeHelper::toDateTime($value)or Carbon with'UTC'. Seereferences/dates-env-database.md. - Magic property access (
$plugin->settings,$app->view) fails PHPStan; use explicit getters (getSettings(),getView()). Seereferences/tooling.md. - Calling Craft-specific methods directly on
Craft::$app— narrow with a typed local:/** @var \craft\web\Application $app */ $app = Craft::$app;. Don't use@phpstan-ignore-line. - Contract constants (permission handles, wire formats) duplicated as
private constdrift silently: onepublic conston the owner, e.g.SettingsController::PERMISSION_MANAGE_SETTINGS. Seereferences/naming-conventions.md. - Permission handles are kebab-case (
handle:manage-settings); never camelCase, though Craft core's own are camelCase. The PHP constant staysSCREAMING_SNAKE_CASE. Seereferences/naming-conventions.md. App::env('VAR'), nevergetenv(), in plugin code and in every config example (withuse craft\helpers\App;).App::parseEnv()for settings that may hold a$VARor alias. Seereferences/dates-env-database.md.- The same authorization check written separately in a CP controller, a console command, and a GraphQL resolver drifts: one shared gate called by every surface, a test per surface. Console is not exempt; GraphQL schema scope is not the plugin's permission matrix. Craft has no self-approval guard either. See
references/authorization-parity.md. ../*path repositories in a plugin'scomposer.jsonresolve only on the author's disk. Seereferences/tooling.md(Composer Hygiene).Db::parseParam()for a literal comparison turns a leading/trailing*into aLIKEwildcard. UseandWhere(['col' => $value]).- Registering
EVENT_REGISTER_ELEMENT_TYPES/EVENT_REGISTER_FIELD_TYPESinside agetIsCpRequest()branch hides the type from console/queue requests (andGcstops purging it). Register unconditionally. Seereferences/dates-env-database.md. - Console controller docblocks print verbatim as
craft help: the summary is physical docblock line 2, so no=========rule there, no{@see}/{@link}/{@inheritdoc}, no scaffolded* Class FooController. Seereferences/phpdoc-standards.md. - Copy style: no em-dashes (—) or en-dashes (–) in user-facing copy (
Craft::t()strings, labels, CP notices, console output, README, docs). Code comments and PHPDoc are exempt. Seereferences/templates-and-patterns.md.
Verification Checklist
Before every commit:
ddev composer check-cspassesddev composer phpstanpasses- Tests green
- PHPDocs complete on all new/modified code
@throwschains verified- Section headers present and correct
- Imports flat alphabetical (ECS-enforced, not "PHP globals first")
- No em-dashes (—) or en-dashes (–) in user-facing copy (
Craft::t()strings, labels, CP notices, README, docs)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

