Objectives and prerequisites
By the end of this course, you will be able to read and design a small object model in PHP, place responsibilities in the right place, protect business rules and test the resulting behaviour. The common thread is a catalogue and a cart: products, prices, quantities, discounts and validation errors.
Prerequisites: you have already written a simple PHP script and know variables, arrays and functions. The examples use PHP 8.4 with declare(strict_types=1), property types, readonly classes, enumerations and named arguments. Composer is used for autoloading.
Path: chapters 1 and 2 lay the foundations and show the limits of scattered arrays; chapters 3 to 7 build objects, invariants, value objects and composition; chapters 8 to 10 cover polymorphism, inheritance and injection; chapters 11 and 12 cover organisation, tests and synthesis. Allow about twenty-five minutes of reading and four to five hours of practice.
Convention: files follow PSR-4 in src/ and tests live in tests/. Amounts are stored as integer cents, never floats. The examples are fictional and run with php or PHPUnit. Each chapter ends with a check you can reproduce.
1. The PHP basics you need
PHP runs on the server and produces a response, often HTML. A script starts with <?php and may contain variables, arrays, functions and includes. declare(strict_types=1) enables strict typing for the file: silent conversions between types become errors. This is a useful protection for a business model.
<?php
declare(strict_types=1);
$price = 1250; // €12.50 in cents
$quantity = 3;
$total = $price * $quantity;
function format(int $cents): string
{
return number_format($cents / 100, 2, ',', ' ') . ' €';
}
echo format($total); // 37,50 €
The main scalar types are int, float, string and bool. Arrays may be indexed or associative. A function declares its parameters and its return type; a missing value can be represented by null, provided it is declared. Classes and interfaces are types in their own right.
Associative arrays are handy for carrying data, but they do not express rules. Nothing prevents $product['price'] = -5 or forgetting the price key. An object can reject an invalid value at construction. That is the difference between a passive structure and a model that protects its invariants.
Errors and exceptions are different. A syntax or type error is a code defect; an exception may signal a violated business rule, such as a negative quantity. InvalidArgumentException suits an invalid argument. A dedicated business exception makes the message more precise and lets the caller react.
Finally, use a reproducible environment: a known PHP version, Composer, a composer.json file and runnable tests. A script that depends on undocumented local configuration is hard to maintain. The following chapters assume you can run composer install and vendor/bin/phpunit.
Make a habit of separating code that displays HTML from code that manipulates the domain. A file that mixes echo, calculations and database access is hard to test. The object model can run without a browser, which makes tests fast and reliable.
In a web application, the request arrives at a front controller, which dispatches to code that builds objects and returns a response. The domain objects do not need to know about HTTP, sessions or templates. Keeping them independent from the framework makes them reusable in a command, a test or a background job.
2. Why group state and behaviour
Imagine a cart represented by an array: $cart = ['items' => [], 'total' => 0]. Adding an item, recalculating the total, applying a discount and checking a quantity require separate functions that manipulate that array. Each function must know the exact structure and the implicit rules. A renamed key breaks several places without a type error.
An object groups the state and the operations that concern it. The cart knows its items, its total and its rules. The outside world calls add(), total() or applyDiscount() without manipulating internal details. If the structure changes, only the object changes. This encapsulation reduces the error surface.
// Array version: rules are scattered
$cart = [];
$cart[] = ['product' => 'Notebook', 'price' => 350, 'quantity' => 2];
function total(array $cart): int
{
$total = 0;
foreach ($cart as $line) {
$total += $line['price'] * $line['quantity'];
}
return $total;
}
Grouping does not mean putting everything into a single class. A class that handles products, the cart, payments and emails is a god object that is hard to test. Grouping should follow responsibilities: a product describes a product; a cart composes lines; a strategy computes a discount. Each object has one reason to change.
Behaviour should have a business name. addProduct() is clearer than setItems(). A method that changes state should be explicit, and a method that answers a question should be named like a question: isEmpty(), total(). Names are part of design.
Finally, do not create an object for every detail. A useful object model is smaller than an exhaustive one. Start with the concepts that carry rules and behaviour, then add others when the need appears. Simplicity is a quality of the model, not an admission of weakness.
A good clue for grouping is the question "what happens if this rule changes?". If the quantity-merging rule changes, a single method should change. If the price display format changes, a single value object should change. When several places depend on the same rule, the model is poorly split or the rule is not centralised.
Arrays remain useful at the system boundaries: reading a file, decoding JSON, an HTTP request. Convert them into objects as soon as the data enters the domain. This conversion, often called hydration, isolates validation and prevents raw arrays from circulating in business layers.
Naming also shapes the model. A method called calculateTotal() suggests a computation; getTotal() suggests a stored value. Choose names that match the behaviour and avoid vague verbs like process or handle. Clear names reduce the need for comments and make tests read like specifications.
3. Class, instance, constructor and identity
A class is a template; an instance is an object created from that template. The constructor initialises state. In PHP, new Product(...) creates an instance. Two instances with the same values remain two distinct objects: an object's identity is its reference, not only its content.
final class Product
{
public function __construct(
public readonly string $name,
public readonly Money $price,
) {
}
}
$notebook = new Product('A5 Notebook', Money::fromEuros('3.50'));
$copy = $notebook;
var_dump($notebook === $copy); // true: same object
final prevents inheritance. This is not an obligation, but it is a reasonable default: if inheritance becomes necessary, it can be introduced consciously. readonly prevents a property from changing after construction. A product whose name and price do not change is simpler to reason about than a mutable product shared between carts.
The constructor must establish a valid object. If an empty name or a negative price is forbidden, the constructor must reject it. A partially initialised object forces every method to check state, which scatters the rules. Better to fail at construction than to discover the inconsistency later.
Named arguments improve readability: new Product(name: 'Notebook', price: ...). Default values should remain rare and justified. A constructor with ten parameters often signals a class with too many responsibilities or an object that should be split.
Finally, do not confuse equality and identity. == compares properties; === compares references. For a value object, equality of content may matter; for an entity such as an order, identity matters. The choice must be explicit, and tests must verify the expected behaviour.
A private constructor and a static factory are useful when creation requires validation or conversion. Money::fromEuros() illustrates this pattern: the caller expresses a readable amount, the factory controls the conversion. The constructor remains the only place that sets internal state.
Identity also matters for persistence. A product may be identified by a database identifier, while a value object has no identity beyond its content. Mixing the two creates confusion in repositories and tests. Decide early whether a concept is an entity or a value, and keep that decision consistent.
4. Visibility, encapsulation and invariants
Visibility controls access to properties and methods. public is accessible everywhere, protected within the class and its subclasses, private within the class alone. By default, start private or read-only public, and open only what must be open. A modifiable public property can be changed without going through the rules.
final class CartItem
{
public function __construct(
public readonly Product $product,
private int $quantity,
) {
if ($quantity <= 0) {
throw new InvalidArgumentException('Quantity must be positive.');
}
}
public function quantity(): int
{
return $this->quantity;
}
public function add(int $quantity): void
{
if ($quantity <= 0) {
throw new InvalidArgumentException('Added quantity must be positive.');
}
$this->quantity += $quantity;
}
}
An invariant is a property that is always true for a valid object. For CartItem, the quantity is strictly positive. Every method that changes state must preserve this invariant. If a method can violate it, it must reject the operation or the object must be recreated. Invariants are the foundation of trust in the model.
Encapsulation does not mean putting getters and setters everywhere. A getter that exposes an internal collection lets the outside world modify it. A method that returns a copy or a read-only view protects state better. In PHP, an array is copied on assignment, but a contained object remains shared.
Methods should express business operations, not only reads and writes. add(), remove(), applyDiscount() are richer than setQuantity(). A method that validates a rule along the way avoids duplicating it in callers. The model becomes the single place for the rule.
Finally, test invariants. A test that constructs an invalid object must fail with an exception. A test that calls a forbidden method must verify that state remains unchanged. Encapsulation without tests is an intention; with tests, it is a guarantee.
Visibility must also be justified in the other direction: do not make a method private if it expresses an operation callers must be able to perform. An overly closed class forces callers to work around its interface, often by accessing the database or duplicating the rule. Encapsulation protects state without making the object unusable.
Another trap is the getter that returns an internal mutable object. If Cart::product() returns a modifiable product, the caller can change its price and bypass validation. readonly properties limit this risk, but a collection or an object that is still mutable must be copied or exposed in a read-only form.
5. Typing, nullability, errors and exceptions
Typing makes contracts explicit. A method that expects a Product cannot receive an array by mistake. Return types force a decision about what a method produces. ?Product means the value may be absent; Product means it is always present. Prefer the most precise type possible.
final class Cart
{
/** @var list<CartItem> */
private array $items = [];
public function find(string $name): ?CartItem
{
foreach ($this->items as $item) {
if ($item->product->name === $name) {
return $item;
}
}
return null;
}
}
null must have a precise meaning: no result, value not provided, optional relation. It must not hide an error. If a datum is mandatory and missing, throw an exception or reject construction. A null circulating in the model forces every caller to handle it, often with a forgotten if.
Exceptions propagate to a place that knows what to do. A business exception can be caught by a controller to display a message; a programming exception should generally bubble up and be fixed. Do not mix the two. A broad catch that swallows everything hides bugs and makes diagnosis difficult.
Expected errors can also be represented by an explicit result, such as a Result object or an enumeration. The choice depends on context. For a simple business rule, a dedicated exception is often readable. For form validation that collects several errors, a list of messages is more suitable.
Finally, document exceptions in the method contract. A caller must know what it can catch. Types and exceptions are part of the public interface, just like method names. A method that fails unpredictably is hard to use correctly.
The never type indicates that a function never returns, for example because it always throws. The void and never return types remove ambiguity. Use them when true, and do not return null to signal a failure that should be an exception.
Nullable types should be handled at the boundary. When a controller receives an optional parameter, it can convert absence into an explicit default or reject the request. Do not let null travel deep into the domain where every method must remember to check it.
6. Value objects, prices and immutability
A value object represents a value, not an identifiable entity. Two value objects with the same content are interchangeable. Money, Email, Quantity are typical candidates. They encapsulate a rule: an amount has a currency, an email has a format, a quantity is positive.
final readonly class Money
{
private function __construct(public int $cents)
{
}
public static function fromCents(int $cents): self
{
if ($cents < 0) {
throw new InvalidArgumentException('Amount must be positive.');
}
return new self($cents);
}
public static function fromEuros(string $amount): self
{
return self::fromCents((int) round((float) $amount * 100));
}
public function add(self $other): self
{
return self::fromCents($this->cents + $other->cents);
}
public function multiply(int $quantity): self
{
if ($quantity < 0) {
throw new InvalidArgumentException('Quantity must be positive.');
}
return self::fromCents($this->cents * $quantity);
}
public function format(): string
{
return number_format($this->cents / 100, 2, ',', ' ') . ' €';
}
}
Storing integer cents avoids floating-point errors. 0.1 + 0.2 does not give exactly 0.3 in binary. For amounts, use integers or a decimal library, and convert only for display. The private constructor forces the use of factories that control the conversion.
Immutability means an operation returns a new object instead of modifying the original. add() and multiply() return a new Money. This avoids side effects: a shared price does not change when a total is computed. In return, the result must be reassigned, which makes the flow explicit.
A value object must reject invalid values. A negative amount, an unknown currency or a malformed email must fail at construction. Validation is thus centralised. Callers do not have to repeat the same checks, and the objects that circulate are valid by construction.
Finally, do not use a value object for everything. A technical identifier can remain an integer or a UUID; a display name can remain a string. The criterion is the business rule and the risk of confusion. A Money that prevents adding euros and dollars justifies its complexity; a StringWrapper without a rule adds nothing.
A value object can also carry comparison operations. Money::equals() compares cents and currency; Quantity::isGreaterThan() compares two valid quantities. These methods prevent callers from comparing internal details. They also make tests more expressive.
7. Associations and composition
A cart contains lines; a line contains a product and a quantity. Composition expresses that an object is responsible for the lifetime of its parts. Here, lines belong to the cart: they do not exist independently. The cart can create, modify and remove them.
final class Cart
{
/** @var list<CartItem> */
private array $items = [];
public function add(Product $product, int $quantity): void
{
foreach ($this->items as $item) {
if ($item->product->name === $product->name) {
$item->add($quantity);
return;
}
}
$this->items[] = new CartItem($product, $quantity);
}
public function total(): Money
{
$total = Money::fromEuros('0.00');
foreach ($this->items as $item) {
$total = $total->add($item->product->price->multiply($item->quantity()));
}
return $total;
}
}
A simple association links two independent objects: a product exists even when it is in no cart. Composition is stronger: the part has no meaning without the whole. This distinction guides deletion, persistence and tests. Deleting a cart must not delete the product from the catalogue.
Collections must be protected. Exposing the internal array lets the outside world add an invalid line or bypass quantity merging. An items(): array method can return a copy for reading, while changes go through add() and remove(). The list<CartItem> type documents the intent.
Collaboration between objects must be explicit. The cart does not know the product's calculation details; it asks for the price and multiplies. The product does not know the cart; it ignores where it is used. This separation reduces dependencies and lets the product be reused in a catalogue, an order or a quote.
Finally, test associations: does adding the same product twice merge quantities? Does removing a line update the total? Does an empty cart return zero? These questions reveal implicit rules. A correct object model makes these behaviours explicit and testable.
Line removal must also respect invariants. A remove() method that leaves a line at quantity zero creates an ambiguous state. Remove the whole line or reject the operation. The cart must never contain an empty line, even if the total remains correct.
When a cart is copied, decide what is shared. Copying the array creates a new list, but the Product objects inside remain shared. Since products are readonly, sharing is safe. If products were mutable, a copy would need to duplicate them or the model would need another rule.
8. Interfaces and polymorphism
An interface describes a contract: methods that several classes can implement. Code that depends on the interface does not know the implementation. For discounts, DiscountStrategy can expose apply(Money $total): Money. The cart receives a strategy and applies it without knowing whether it is a fixed discount, a percentage or no discount.
interface DiscountStrategy
{
public function apply(Money $total): Money;
}
final class NoDiscount implements DiscountStrategy
{
public function apply(Money $total): Money
{
return $total;
}
}
final class PercentageDiscount implements DiscountStrategy
{
public function __construct(private int $percent)
{
if ($percent < 0 || $percent > 100) {
throw new InvalidArgumentException('Invalid percentage.');
}
}
public function apply(Money $total): Money
{
return Money::fromCents($total->cents - intdiv($total->cents * $this->percent, 100));
}
}
Polymorphism lets the same method be called on different objects and produce adapted behaviour. The cart has no if for each discount type. Adding a new strategy does not modify the cart, which respects the open/closed principle: open to extension, closed to modification.
An interface must stay small. An interface with ten methods forces every implementation to define all of them, even when it does not need them. Prefer several targeted interfaces. In PHP, a class can implement several interfaces, which allows capabilities to be composed without multiple inheritance.
Strategies must be tested separately. NoDiscount returns the total unchanged; PercentageDiscount(10) removes ten percent. Test the boundaries: 0%, 100%, a zero total, an invalid percentage. The cart should be tested with a fake strategy to verify that it calls the contract.
Finally, do not create an interface for every class. An interface is justified when several implementations exist or when a contract must be stable for callers. An interface with a single implementation can be useful for tests, but it adds indirection. The cost must be justified by a real need.
Polymorphism is not limited to discounts. A cart export can depend on a CartExporter interface with CSV, JSON or HTML implementations. The calling code chooses the implementation and ignores the details. This split makes testing easier and prepares new formats without modifying the cart.
9. Inheritance: how it works and its limits
Inheritance lets a class reuse the behaviour of a parent class. class PercentageDiscount extends Discount inherits methods and can override them. In PHP, a class can inherit from only one class but can implement several interfaces. Inheritance creates strong coupling between parent and child.
abstract class Discount
{
public function apply(Money $total): Money
{
return $this->doApply($total);
}
abstract protected function doApply(Money $total): Money;
}
Inheritance suits cases where the child is genuinely a specialisation of the parent and shares its contract. It is misleading when the child reuses only part of the behaviour or must disable methods. Inheritance that forces "unsupported" exceptions is often a sign that composition would be more appropriate.
Composition delegates to an object instead of inheriting. The cart can hold a discount strategy instead of inheriting from a cart class. Composition is more flexible: the strategy can change at runtime, be tested in isolation and avoid deep hierarchies. It is often preferable for variable behaviour.
Inheritance remains useful for stable, shallow hierarchies, such as business exceptions or genuinely related content types. Even then, keep classes small and contracts clear. A five-level hierarchy is hard to understand and evolve.
Finally, prefer final by default. If a class is not designed for inheritance, allowing it exposes internal details and enables fragile subclasses. Open inheritance when you have a concrete need and can document the protected contract. Composition is often the safer choice.
A useful test is to ask whether the child can replace the parent everywhere without surprise. If a subclass changes the meaning of a method or rejects an operation that is valid for the parent, the contract is violated. This substitution principle guides design: a hierarchy must not lie about its capabilities.
10. Responsibilities, dependencies and injection
A class must have a clear responsibility. The cart computes a total; it does not save to a database, send emails or format HTML. Those responsibilities belong to other objects. A class that changes for several reasons is hard to test and maintain.
final class Cart
{
public function __construct(
private DiscountStrategy $discount = new NoDiscount(),
) {
}
public function totalWithDiscount(): Money
{
return $this->discount->apply($this->total());
}
}
Dependencies must be explicit. If the cart needs a strategy, receive it in the constructor instead of creating it inside. Dependency injection lets an implementation be replaced by another, especially in tests. It also makes dependencies visible when reading the code.
Do not confuse injection and container. Injection is a principle: pass what the object needs. An injection container is a tool that assembles objects. You can practise injection without a container, and a container does not fix poor responsibility splitting.
Dependencies must be stable and abstract where useful. Depending on an interface for a variable strategy is reasonable; depending on a concrete class for a stable feature may suffice. Avoid systematic abstraction: an interface without variation adds noise. The criterion is testability and the likelihood of change.
Finally, test collaborations. A cart with a fake strategy must call the strategy once and use its result. A test that only checks the final total can pass even if the strategy is not called. Collaboration tests complement result tests.
An optional dependency must have a safe default. Here, NoDiscount ensures that a cart without a discount works without configuration. Avoid optional dependencies that leave the object in an unusable state; prefer an object that is always ready to use.
Responsibilities can be checked with a simple question: how many reasons does this class have to change? A cart that changes when tax rules change and when the email template changes has at least two. Split it, or delegate the second concern to a collaborator.
11. Composer, autoloading and namespaces
Composer manages dependencies and autoloading. A composer.json file declares the project name, dependencies and PSR-4 configuration. composer install installs the versions locked by composer.lock. composer dump-autoload regenerates the class map.
{
"name": "kelia/shop",
"require": {
"php": ">=8.4"
},
"require-dev": {
"phpunit/phpunit": "^11.0"
},
"autoload": {
"psr-4": {
"Kelia\\Shop\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Kelia\\Shop\\Tests\\": "tests/"
}
}
}
PSR-4 maps a namespace prefix to a directory. The class Kelia\Shop\Cart is looked up in src/Cart.php. The path must match case and tree exactly. A misnamed or misplaced class will not be loaded, even if the file exists.
Namespaces avoid collisions between classes with the same name. Use a stable prefix, such as the company or project name. use imports make code readable. Avoid generic names like Util or Manager: they attract several responsibilities and become catch-alls.
Organise by domain, not only by technical type. A Cart/ directory containing Cart.php, CartItem.php and DiscountStrategy.php is more readable than a Models/ directory with every class. Organisation must reflect the model, not a fashion.
Finally, version composer.lock for an application; do not version it for a reusable library. Install with --no-dev in production and verify that the optimised autoloader works. A deployment that depends on a forgotten composer dump-autoload fails at the first class load.
Composer scripts can automate checks: tests, static analysis, formatting. A check script that runs PHPUnit and PHPStan gives a single entry point. Document it in the README so every developer runs the same verifications before delivering.
Dependency versions should be constrained but not frozen unnecessarily. A caret constraint allows compatible updates while the lock file records the exact versions used. Review updates deliberately, run the tests, and commit the lock file with the change. This keeps builds reproducible and upgrades visible.
12. Tests, debugging and synthesis
An object test verifies observable behaviour. For the cart, test adding, quantity merging, the total, the discount and errors. A test must be isolated: it creates its objects and does not depend on a database or execution order. PHPUnit provides assertions and exception handling.
final class CartTest extends TestCase
{
public function testEmptyCartHasZeroTotal(): void
{
$cart = new Cart();
self::assertSame(0, $cart->total()->cents);
}
public function testAddingSameProductMergesQuantities(): void
{
$cart = new Cart();
$product = new Product('Notebook', Money::fromEuros('3.50'));
$cart->add($product, 2);
$cart->add($product, 3);
self::assertSame(5, $cart->items()[0]->quantity());
}
}
Test nominal cases first, then boundary cases: empty cart, quantity of one, invalid quantity, 0% discount, 100% discount, zero total. A test that only checks the happy path gives false confidence. Exceptions must be tested with expectException and a precise type or message.
Debugging an object starts by checking its state. var_dump or symfony/var-dumper shows properties, but an object may hide details through encapsulation. Use public methods and tests to observe behaviour. A step debugger helps follow calls and modifications.
Frequent errors are shared mutation, partially valid objects, setters that violate invariants, hidden dependencies and mixed responsibilities. A class that knows too much becomes hard to test. A successful object model reads like a description of the business.
The synthesis of the common thread: Money protects amounts, Product describes a product, CartItem carries a valid quantity, Cart composes lines and computes the total, DiscountStrategy makes the discount interchangeable. Each object has a contract, invariants and tests. The whole evolves without breaking everything.
To go further, explore value objects, enumerations, typed collections and SOLID principles. But keep the model small and readable. The quality of an object model is measured by its ability to express business rules and withstand change, not by the number of classes.
A final piece of advice: read your model aloud. If you cannot explain a class in one sentence, it probably has several responsibilities. If you cannot name an invariant, the class may be a simple data structure. Business language is the best guide for splitting.
Exercise 1 — From array to object
The following code manipulates a product as an array: ['name' => 'Notebook', 'price' => 350]. Write a Product class with a non-empty name and a Money price. Explain what the object prevents that the array allowed.
Solution
Product receives a name and a Money in its constructor, throws if the name is empty and exposes read-only properties. The array allowed a negative price, a missing key or an inconsistent type. The object guarantees that an existing product is valid and makes errors visible at construction.
Exercise 2 — Quantity invariant
Write CartItem with a strictly positive quantity and an add() method. Test construction with 0 and -1, then adding a negative quantity. What must happen?
Solution
The constructor throws InvalidArgumentException if the quantity is less than or equal to zero. add() does the same for an invalid added quantity. The object must never exist with a zero or negative quantity. Tests verify the exception type and that state remains unchanged after a rejected add.
Exercise 3 — Money value object
Implement Money in cents with add(), multiply() and format(). Why avoid float? Test €0.01 added one hundred times.
Solution
Money stores an integer number of cents and returns new objects. float introduces binary approximations: 0.01 is not exact, and one hundred additions may produce 0.999999… instead of 1.00. With cents, addition is exact. The test verifies that one hundred times 1 cent gives 100 cents and that formatting displays €1.00.
Exercise 4 — Cart composition
Add the same product twice to the cart. What quantity do you get? Add a different product. Compute the total. What happens when the cart is empty?
Solution
The cart merges lines for the same product and adds the quantities. A different product creates a new line. The total is the sum of prices multiplied by quantities. An empty cart returns Money at zero. Tests cover merging, a distinct add, the total and the empty cart.
Exercise 5 — Discount strategy
Implement NoDiscount and PercentageDiscount. Test 0%, 10%, 100% and an invalid percentage. Explain why the cart must not contain an if on the discount type.
Solution
NoDiscount returns the total. PercentageDiscount validates the percentage between 0 and 100 and computes the reduction in cents. The cart depends on the interface, not the implementations: adding a fixed discount does not modify the cart. Tests cover boundaries and the invalid percentage. Polymorphism replaces conditions with interchangeable objects.
Exercise 6 — Tests and injection
Write a test that verifies the cart calls the discount strategy. Inject a fake strategy that records the call. Why can a total-only test pass without proving the call?
Solution
The fake strategy implements DiscountStrategy, increments a counter in apply() and returns the total. The test checks the counter and the result. A total-only test can pass if the cart ignores the strategy and returns the unchanged total, or if the discount is zero. The collaboration test proves the contract is used.
Capstone — catalogue and cart
Deliver a small object model with Money, Product, CartItem, Cart and two discount strategies. The cart must merge lines, reject invalid quantities, compute an exact total and apply an injected discount. Add tests for nominal, boundary and error cases, plus a note explaining responsibilities and immutability choices.
Grading: objects valid by construction; protected invariants; amounts in cents; clear composition; justified discount interface; injected dependencies; isolated and readable tests; working autoloading. A model without tests or responsibility justification is not complete.
Common mistakes and debugging method
Classic mistakes are unvalidated associative arrays, modifiable public properties, setters that violate an invariant, partially constructed objects, dependencies created inside a class, deep inheritance hierarchies and catch-all classes. Using float for amounts is one of them.
Method: reproduce with a small object, check state after each method, state the invariant, then fix the cause. Add a regression test. If an object is hard to test, the dependency or responsibility is probably misplaced. The test often reveals the design flaw before the bug.
Self-assessment
You must be able to explain the difference between class and instance, choose property visibility, state an invariant, distinguish value object and entity, compose a cart, define an interface, compare inheritance and composition, inject a dependency, organise autoloading and test behaviour.
Self-assessment: I can replace an array with a valid object; I can protect a quantity; I can compute an amount without floats; I can add a strategy without modifying the cart; I can test an exception; I can justify a dependency. To progress, study SOLID principles, typed collections and property-based tests.
If several answers remain unclear, revisit the common thread and write the complete model without copying the examples. Regular practice on a small domain is more formative than passive reading. Then add boundary cases to your tests: that is where design flaws appear.
References
- PHP — Classes and Objects, accessed 23 October 2026.
- PHP — Type declarations, accessed 23 October 2026.
- PHP — Basic syntax, accessed 23 October 2026.
- Composer — The composer.json schema, accessed 23 October 2026.
- PSR-4 — Autoloading Standard, accessed 23 October 2026.
- PHPUnit 11 — Documentation, accessed 23 October 2026.
- Martin Fowler — ValueObject, accessed 23 October 2026.