Putting it together

Intermediate

Introduction

Now you put everything together. A real program is not one trick but a small design: it reads commands, keeps data in a class, enforces rules with exceptions, and prints a clear report. In this lesson you read a complete command-line program, an inventory manager, and learn how to plan a program of your own. You will use almost every idea of this course: input, strings, arrays, functions, classes and exceptions.

How it works

Start with a plan. First write down what the program must do in plain words: "add items, remove items, print a sorted report, print the total, and say when something is wrong". Then find the nouns and the verbs. The nouns, here the inventory and its items, become data and classes. The verbs, here add, remove, report and total, become methods.

A good structure has three layers:

  1. Input: a loop that reads lines until the input ends, with while (($line = fgets(STDIN)) !== false). It trims the line and splits it with explode(" ", $line) into a command and its arguments.
  2. Logic: a class that owns the data and the rules. In the example, Inventory keeps an array of names and quantities. It is the only code that touches the array, so every rule is in one place.
  3. Output: the loop prints a short line for each command, and the report is printed with str_pad so that the columns line up.

Rules are enforced with exceptions. The class throws InvalidArgumentException for a quantity that is not positive, and your own OutOfStock exception when you try to remove more than you have. The loop wraps each command in try and catch, prints error: ... and continues with the next line, so a bad command never stops the program. Unknown commands get a message too, using the default case of the switch.

Test in small steps. Write the class first and try one command. Then add the loop. Test the normal case, then the edge cases: an empty line, an unknown command, removing everything of an item, and adding an item twice. In the example, an item whose quantity reaches zero is removed from the array with unset, so it does not appear in the report. Sorting a copy with ksort keeps the stored data untouched.

Last, read your program again as a stranger would. Are the names clear? Is each method short? Does each class do only one job? This is the habit that turns working code into good code.

Example

<?php
class OutOfStock extends Exception
{
}

class Inventory
{
    private array $items = [];

    public function add(string $name, int $qty): void
    {
        if ($qty <= 0) {
            throw new InvalidArgumentException("Quantity must be positive");
        }
        $this->items[$name] = ($this->items[$name] ?? 0) + $qty;
    }

    public function remove(string $name, int $qty): void
    {
        $have = $this->items[$name] ?? 0;
        if ($have < $qty) {
            throw new OutOfStock("Only $have of $name");
        }
        $this->items[$name] = $have - $qty;
        if ($this->items[$name] === 0) {
            unset($this->items[$name]);
        }
    }

    public function report(): array
    {
        $copy = $this->items;
        ksort($copy);
        return $copy;
    }

    public function total(): int
    {
        return array_sum($this->items);
    }
}

$inventory = new Inventory();
while (($line = fgets(STDIN)) !== false) {
    $line = trim($line);
    if ($line === "") {
        continue;
    }
    $parts = explode(" ", $line);
    $command = $parts[0];
    try {
        switch ($command) {
            case "add":
                $inventory->add($parts[1], (int) $parts[2]);
                echo "added {$parts[2]} {$parts[1]}\n";
                break;
            case "remove":
                $inventory->remove($parts[1], (int) $parts[2]);
                echo "removed {$parts[2]} {$parts[1]}\n";
                break;
            case "report":
                foreach ($inventory->report() as $name => $qty) {
                    echo str_pad($name, 8), $qty, "\n";
                }
                break;
            case "total":
                echo "total ", $inventory->total(), "\n";
                break;
            default:
                echo "unknown command: $command\n";
        }
    } catch (OutOfStock | InvalidArgumentException $e) {
        echo "error: ", $e->getMessage(), "\n";
    }
}

Input used: add pear 5 ⏎ add apple 3 ⏎ add pear 2 ⏎ remove apple 1 ⏎ remove apple 9 ⏎ add kiwi 0 ⏎ report ⏎ fly away ⏎ total

Line by line

  1. OutOfStock is a custom exception, and Inventory holds the items in a private array.
  2. add checks the quantity and adds it to the old amount, using ?? 0 for a new item.
  3. remove throws when there is not enough, and deletes an item whose quantity reaches zero.
  4. report returns a sorted copy, and total adds all quantities.
  5. The main loop reads each line, splits it and chooses the action with switch.
  6. Both exception types are caught in one block, so a bad command prints an error and the loop goes on.

Expected result

With this input:

add pear 5
add apple 3
add pear 2
remove apple 1
remove apple 9
add kiwi 0
report
fly away
total

it prints:

added 5 pear
added 3 apple
added 2 pear
removed 1 apple
error: Only 2 of apple
error: Quantity must be positive
apple   2
pear    7
unknown command: fly
total 9

In the real world

Command-line scripts like this one run in every company: they import data, send reports, clean databases and prepare backups. A web application is built in the same way, with input handled at the edge, rules inside classes and clear errors. Once you can structure a small program well, you can read and extend large ones.

Common mistakes

  • Writing everything in one long block, which is hard to test and change.
  • Not trying edge cases such as empty input or unknown commands.
  • Letting the data be changed from outside the class.
  • Stopping the whole program on a single bad line instead of catching the exception.

Best practices

  • Plan first: list what the program must do, then the nouns and verbs.
  • Keep input, logic and output apart.
  • Throw exceptions for broken rules and catch them where you can respond.
  • Test one command at a time, then the edge cases.

Summary

A complete program reads input in a loop, passes commands to a class that owns the data and rules, and prints clear results. Exceptions report broken rules without stopping the program. Plan with nouns and verbs, keep layers apart, and test the normal and the edge cases.

Quick check

1. Where should the rules of the data live?
2. Why is each command wrapped in try and catch in the loop?
3. What is a good first step when you plan a program?
4. Why does report() sort a copy of the array?

Key takeaways

  • Keep input, logic and output apart.
  • Let one class own the data and its rules.
  • Catch exceptions in the loop so one bad command never stops the program.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.