Architecture

Designing Testable PHP Code

Structure PHP code so important behavior can be verified without booting the entire application.

Overview

Testability is an architectural property. Code is easier to test when business decisions are separated from HTTP input, database access, global state and external services.

Separate decisions from effects

Keep calculations and policy decisions in focused classes or functions. Put effects such as sending email, reading the clock and calling a remote API behind small interfaces. The application layer can coordinate these pieces while tests provide controlled implementations.

Avoid hidden dependencies

Global variables, direct calls to $_SESSION, $_POST, mail() and time() make behavior harder to isolate. Pass required values explicitly or wrap the operation in a dependency.

Example

A subscription service can receive a ClockInterface and a PaymentGateway rather than constructing them internally. A test can then supply a fixed clock and a fake gateway to verify expiry and payment decisions deterministically.

Practical review

When a test requires a full web server, production credentials and a live third-party account just to check a business rule, consider whether the code has too many responsibilities.

Share this page Help other developers discover this resource.