Documentation · Chapter 14

Organize a console program with objects.

Classes become useful when data and behavior belong together. Console projects use the same namespaces, autoloading, strict types, and tests as larger PHP applications.

Every lesson starts from the problem, explains the mechanism, then gives a concrete verification.

LESSON OBJECTIVE

What you will be able to do

Move domain behavior into typed classes and make it testable without waiting for interactive input.

Keep Program small

Program coordinates the conversation; domain classes calculate, validate, or transform. This keeps the exercise understandable as it grows.

phpaml — zsh
final class Cart
{
    /** @param list<int> $prices */
    public function total(array $prices): int
    {
        return array_sum($prices);
    }
}

Use typed collections

PHP arrays can hold lists and maps. PHPStan annotations such as list<User> add static precision without inventing non-PHP generic syntax.

Test behavior without typing manually

Inject values or streams into testable services. Tests should not depend on a human entering text at the right moment.

CHECKPOINT

Before you continue

Can the calculation class be tested with ordinary arguments and no terminal attached?