Library contents

PHP LogicException

The checkout code can enforce its paid state by throwing a LogicException on an invalid transition.

A simple example

LogicException

  1. Start with A record marked closed
  2. Do this Try adding a new item
  3. Result Operation rejected
The same item could be added while the record was open. Its current state prevents the change.

Syntax

PHP syntax
throw new LogicException($message)
Run these examples in PHP

Save one example at a time as lesson.php. Use PHP 8.2 or later.

php lesson.php

Add an item after checkout closes

A bakery sends a paid order to the kitchen and locks the ticket. If a second cashier tries to add a pastry, the register needs to explain why the order can no longer change.

From the program$items = []
ResultOrder is closed
lesson.php
<?php
$paid = true;
$items = [];
try {
    if ($paid) {
        throw new LogicException('Order is closed');
    }
    $items[] = 'Pastry';
} catch (LogicException $closed) {
    echo $closed->getMessage();
}
Output
Order is closed

The paid flag blocks the edit before another pastry enters the kitchen order.

Advertisements

Edit a draft outing

An organizer adds a stop while the trip is still a draft. Allow a change only while the booking is open. A closed booking requires a separate amendment.

GivenOpen draft
Worked resultChange accepted

Protect a printed manifest

The clerk tries to edit an outing after its manifest has been finalized. Allow a change only while the booking is open. A closed booking requires a separate amendment.

GivenFinalized manifest
Worked resultStart amendment

What to watch for

Place the state check before changing any order items.

Documentation for LogicException