7 Real-World PHP 8.5 Pipeline Operator Use Cases That Simplify Your Code
This article showcases seven practical PHP 8.5 pipeline operator examples—from cleaning user input and processing CSV rows to building HTTP responses, preparing search queries, calculating cart totals, enriching logs, and creating image thumbnails—demonstrating how the operator makes code more readable and functional.
Introducing the PHP 8.5 Pipeline Operator
The new |> operator lets the result of the left‑hand expression be passed as the first argument to the function on the right, enabling a clear, functional‑style chain of transformations.
API String Cleaning
Normalize a raw username by trimming whitespace, converting to lowercase, and replacing internal spaces with hyphens.
$raw = " ShaoBo Wan ";
$username = $raw
|> trim(...)
|> strtolower(...)
|> (fn($x) => preg_replace('/\s+/', '-', $x));
// Output: "john-doe"Processing Uploaded CSV Rows
Normalize each row, filter out invalid entries, and map them to DTO objects.
$rows = [
['name' => ' Widget A ', 'price' => '12.99', 'sku' => 'W-A'],
['name' => 'Widget B', 'price' => 'n/a', 'sku' => 'W-B'], // invalid price
['name' => 'widget c', 'price' => '7.5', 'sku' => 'W-C'],
];
$products = $rows
|> (fn($xs) => array_map('normalizeRow', $xs))
|> (fn($xs) => array_filter($xs, 'isValidRow'))
|> (fn($xs) => array_map(Product::fromArray(...), $xs));
// Output: [Product('Widget A', 12.99, 'W-A'), Product('Widget C', 7.5, 'W-C')]HTTP Response Construction
Chain encoding, compression, and base64 encoding to produce a compact response body.
$data = ['msg' => 'hello', 'n' => 3];
$body = $data
|> json_encode(...)
|> (fn($x) => gzencode($x, 6))
|> base64_encode(...);
// Output: H4sIAAAAAAAAA2WOuwrCMBBE…Search Query Preparation
Trim, lowercase, strip punctuation, split into tokens, and filter short tokens.
$query = " Hello, WORLD! ";
$tokens = $query
|> trim(...)
|> strtolower(...)
|> (fn($x) => preg_replace('/[^\w\s]/', '', $x))
|> (fn($x) => preg_split('/\s+/', $x))
|> (fn($xs) => array_filter($xs, fn($t) => strlen($t) > 1));
// Output: ['hello', 'world']E‑Commerce Cart Total Calculation
Apply a discount function, sum the results, then apply tax—all without temporary variables.
$cartItems = [
['price' => 100, 'discount' => 0.10],
];
$total = $cartItems
|> (fn($xs) => array_map('priceAfterDiscount', $xs))
|> array_sum(...)
|> (fn($sum) => applyTax($sum));
// Output: 99.0Log and Metric Enrichment
Attach a timestamp, request ID, and IP address to an event, then redact sensitive fields before logging.
$incomingEvent = [
'user' => 'alice',
'email' => '[email protected]',
];
$event = $incomingEvent
|> (fn($x) => array_merge($x, ['received_at' => 1696195560]))
|> (fn($x) => array_merge($x, ['request_id' => '9f2a1c0b7e3d4a56']))
|> (fn($x) => array_merge($x, ['ip' => '203.0.113.42']))
|> (fn($x) => redactSensitive($x));
/* Result example:
[
'user' => 'alice',
'email' => 'a***@example.com',
'received_at' => 1696195560,
'request_id' => '9f2a1c0b7e3d4a56',
'ip' => '203.0.113.42',
]
*/Image Processing Pipeline (Thumbnail Generation)
Load an image, resize, watermark, and optimize it for web delivery using a clear chain of single‑argument functions.
$imagePath = '/images/source/beach.jpg';
$thumb = $imagePath
|> (fn($p) => imagecreatefromjpeg($p))
|> (fn($im) => resizeImage($im, 320, 240))
|> (fn($im) => applyWatermark($im))
|> (fn($im) => optimizeJpeg($im, 75));
// Output: '/images/thumbs/beach_320x240_q75.jpg'Each example demonstrates how the pipeline operator turns verbose, imperative code into concise, readable, and testable functional pipelines.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
