/php-deal:design-by-contractfrom PhpDeal: Design by Contract
Turns business specifications into self-checking PHP code using php-deal/framework: #[Verify] preconditions, #[Ensure] postconditions, #[Invariant] invariants, plus PHPUnit tests from contracts.
Ships in PhpDeal: Design by Contract. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Turn a business specification into PHP code that checks its own rules on every call, and into tests that exercise those rules. PhpDeal reads the contracts from native attributes. They hold PHP expressions as strings, and Go! AOP evaluates them around the method:
use PhpDeal\Attribute\{Ensure, Invariant, Verify};
#[Invariant('$this->balance >= 0')] // always true between calls
class Account
{
private int $balance = 0;
#[Verify('$amount > 0')] // the caller's obligation, checked before the body
#[Ensure('$this->balance === $__old->balance + $amount')] // the method's promise, checked after it
public function deposit(int $amount): void
{
$this->balance += $amount;
}
}
A broken contract throws PreconditionViolation, PostconditionViolation or InvariantViolation. A contract
violation always means a bug in the caller or in the method. It never means invalid user input.
Copy this checklist and work through it:
- [ ] 1. Check the project setup
- [ ] 2. Extract the rules from the specification and number them
- [ ] 3. Classify every rule: precondition, postcondition, invariant, business error or not a contract
- [ ] 4. Design the API: classes, interfaces, query methods for the preconditions
- [ ] 5. Write the code with its contracts
- [ ] 6. Run the contract checker, fix every error
- [ ] 7. Derive the tests and run them
- [ ] 8. Report the rule-to-contract table, the assumptions and the open questions
composer.json requires php-deal/framework (2.x) and PHP 8.4 or newer. If it does not, ask before adding the
dependency with composer require php-deal/framework. Without a composer.json you can inspect, rely on the weaving
check in step 7: one test that breaks a precondition must throw PreconditionViolation.ContractApplication::getInstance()->init([...]) must run before the
classes are autoloaded, in the front controller and in the test bootstrap. Its includePaths must cover the
directory of the new classes. If the project already has its own Go! AOP kernel, it calls
ContractApplication::registerAspects($container) instead. Without weaving the attributes do nothing, so tests
pass without checking anything.Read the specification and list every statement that constrains state, input, output or behaviour. Give each one a
stable ID (R1, R2, ...), or keep the IDs the specification already uses. Quote the source wording. Do not invent
rules. When the specification is ambiguous or silent, write the question down and pick the most conservative
assumption, which is usually the stricter precondition. Data that the API needs but the specification only implies,
such as an id or the name of the person who acts, is API design: add it, list it as an assumption (A1, A2, ...),
and constrain it only as far as the code needs.
| The specification says... | Use |
|---|---|
| "only when", "must be", "at most", "requires": a condition the caller can check first | #[Verify] on the method |
| "after X...", "increases by", "returns", "never changes Y": an effect of the call | #[Ensure] with $__old / $__result |
| "always", "never", "at all times": a fact about the object | #[Invariant] on the class or interface |
| "is rejected with the message...", "show an error": input from people or systems | Code that throws a domain exception, plus #[Ensure] for the success path |
| Timing, notifications, persistence, permissions, other services | Not a contract: integration tests or code |
Two points need judgement:
available(), canCancel()) so that it can check a precondition before the call.$this->total === $__old->total + $amount to $this->total > $__old->total. Add frame conditions for state that
must not change: #[Ensure('$this->reserved === $__old->reserved')].references/spec-to-contracts.md has a catalogue of rule patterns with their contracts: ranges, state machines, collections, uniqueness, implications, money and dates.
#[Inherit]. Without it the interface's preconditions do not apply, and a class that declares no contract
attribute of its own is not checked at all.#[Verify('$this->isValidTransition($to)')]). Contracts run in the
scope of the class, so they can call private methods and read private properties.Expression rules. Every one of them breaks contracts silently when ignored:
#[Verify('$amount > 0')]. In double quotes PHP would interpolate $amount.use imports inside expressions. Write class names fully qualified (\App\Money::isValid($amount)), and
global functions with a leading backslash (\count($items)). self::, static:: and parent:: work.\min($amounts) > 0), because comparing the list with a number ($amounts > 0) is always true.$__result (return value) and $__old (clone of the object before the call) exist only in #[Ensure]. $__old
is a shallow clone: compare scalars, or add a __clone() that copies mutable objects.true (holds), false (violated) or null (for assertion libraries). Any other value throws
InvalidContractException.$this in static methods.#[Verify] and #[Ensure] work on every method: constructors, private, protected and static ones. Invariants are
checked after the constructor and after every public method, not after private ones. final classes are
woven as well.$__result is always null and $__old is the object before its properties are set: check
$this instead.references/expressions.md has the full reference and the pitfalls of floats, dates, enums, collections and nullables.
Add the rule ID next to each contract, as a trailing comment or in the method docblock, so that a reader can trace it back to the specification.
PHP and PHPStan do not see inside the expression strings. Run the bundled checker on the files you wrote:
php ${CLAUDE_SKILL_DIR}/scripts/lint-contracts.php --strict src/Inventory
${CLAUDE_SKILL_DIR} is the directory of this file. In projects with php-deal installed the checker is also at
vendor/php-deal/framework/skills/design-by-contract/scripts/lint-contracts.php. It reports syntax errors, unknown
or misspelled variables, $__old or $__result in the wrong contract, $this in static methods, imported names
that do not resolve, double-quoted strings, assignments, the current time or random values, and \in_array()
without true. Fix every error and warning. It can not check types or the existence of properties: the tests in the
next step do that.
Postconditions and invariants are checked on every call of a woven class. Any test that drives the object through valid calls therefore also tests them. Write these tests:
#[Verify], call just inside the boundary (it passes) and just outside it
(PreconditionViolation, and the state is unchanged). This test also proves that weaving is active.Random\Randomizer and run a
few hundred calls. The contracts check every step.references/testing.md explains each kind and shows the bootstrap. Run the tests. When one of them reports a violation, decide whether the code, the contract or the test is wrong. Do not weaken a contract to make a test pass unless the specification supports the weaker version.
End with:
Rule | Contract or code | Where | Test, with one row per rule (Where is Class::method, or Class for
an invariant);examples/inventory/ holds a complete run: SPEC.md (rules R1-R9), StockItem.php with its contracts, CountBelowReserved.php for the one business error, and StockItemTest.php with the four kinds of tests. Read it before the first implementation in a project. The PhpDeal test suite runs it, so it always works.
examples/inventory/CountBelowReserved.php (opens in a new tab)examples/inventory/SPEC.md (opens in a new tab)examples/inventory/StockItem.php (opens in a new tab)examples/inventory/StockItemTest.php (opens in a new tab)references/expressions.md (opens in a new tab)references/setup.md (opens in a new tab)references/spec-to-contracts.md (opens in a new tab)references/testing.md (opens in a new tab)scripts/lint-contracts.php (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub php-deal/framework --plugin php-dealOther plugins' skills for the same job