Page
1
P H P P ro g ra m m in g in th e A I E ra First Edition D oug Bierer Rainier Sarabia Use GenAI prompts to generate, refactor, and optimize PHP classes and functions Create high-performance apps using JIT, OPcache, and async programming Build secure web apps with session protection, encryption, CAPTCHA, and token-based forms Work with databases using AI-generated queries and caching strategies Design scalable systems with OOP, design patterns, and microservices Develop REST APIs, WebSockets, and real-time applications using AI assistance Apply test-driven development with AI-generated acceptance criteria and automated tests WHAT YOU WILL LEARN PHP off ers several powerful features, but many developers struggle to apply them eff ectively in real-world applications while maintaining performance, security, and code quality. This book addresses that challenge by combining modern PHP practices with generative AI to help you build faster and more reliably. You will work through hands-on recipes that show how to design, generate, and refi ne PHP 8 applications using AI alongside proven engineering techniques. From writing clean object-oriented code and designing scalable architectures to automating repetitive tasks, you will learn how to use AI as a development aid without losing control over quality. As you progress, you will optimize applications using OPcache, JIT, and async programming, while applying secure coding practices and modern design patt erns. The book also explores real-world use cases, including REST APIs, microservices, WebSocket applications, and database-driven systems, helping you translate concepts into production-ready solutions. You will also learn how to modernize legacy PHP codebases, validate AI-generated code, and integrate testing workfl ows to improve reliability and maintainability. Additionally, you will understand how to enhance PHP websites by making API calls to GenAI platforms. By the end of this book, you will be able to combine PHP and generative AI eff ectively to build secure, high- performance applications ready for real-world deployment. www.packtpub.com PHP Programming in the AI Era Get a free PDF of this book packtpub.com/unlock/9781835889923
Page
2
PHP Programming in the AI Era First Edition Build faster PHP applications using GenAI, modern PHP features, and production-ready workflows Doug Bierer Rainier Sarabia
Page
3
PHP Programming in the AI Era First Edition Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Portfolio Director: Ashwin Nair Relationship Lead: Bhavya Rao Project Manager: Vishnu Priya R Content Engineer: Runcil Rebello Technical Editor: Arjun Varma Copy Editor: Runcil Rebello Indexer: Rekha Nair Proofreader: Runcil Rebello Production Designer: Salma Patel Growth Lead: Priyadarshini Sharma First published: July 2026 Production reference: 1140726 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK. ISBN 978-1-83588-992-3 www.packtpub.com
Page
4
To my beloved wife, Nimol, for her never-ending patience and encouragement. To Miquéias Vinícius, for his ceaseless curiosity about new technologies. – Doug Bierer In memory of my beloved sister, Jenina. To Eloise, who has always supported my growth, and to my partner in life, Frezel. – Rainier Sarabia
Page
5
Contributors About the authors Doug Bierer has been hooked on computers since his first program, written in Dartmouth BASIC on a DEC PDP-8, in 1971. In his wide-ranging career, this author has been a professional contract programmer since 1978, having written applications in BASIC, PL/I, assembler, FORTH, C, C++, dBase/FoxBase/Clipper, Pascal, Perl, Java, and PHP. While attending and teaching at Golden Gate University in San Francisco, he took his first AI course in 1986 and has been working extensively with modern AI technology since January 2023. He speaks 4.5 languages, has traveled extensively, and has lived in the USA, France, the Netherlands, England, Sweden, Scotland, Thailand and Cambodia. He is also an accomplished musician (he has written over 60 songs) as well as a writer, under the pen name of Douglas Alan. Doug's own company is unlikelysource.com, which specializes in consulting, PHP programming, website development, and training (primarily for Zend by Perforce). His works of fiction are The End, And Then? and Further Indications. I would like to thank my managers at GSPANN, Saurabh Madan and Rolf Kraus for leading the charge into modern AI tools. I would also like to acknowledge my friend and mentor, Andrew Caya, for his insights and encouragement. Finally, I would like to give a shout out to Matthew Weir O'Phinney and Beth Weinberger at Perforce for their roles in keeping the PHP ecosystem alive and kicking.
Page
6
Rainier Sarabia is a Director of Engineering at Deel and the author of Test-Driven Development with PHP 8 (Packt). An Australian enterprise architect based in Melbourne, he has over 20 years of experience designing scalable, distributed systems and high-quality software. At Deel, he leads seven engineering teams while architecting AI-driven solutions and orchestration frameworks that power complex financial and operational workflows. He stays deliberately hands-on—designing and building alongside his teams to tackle large, high- stakes problems. A language-agnostic engineer fluent in PHP, C#, TypeScript, Java, JavaScript, and SQL, Rainier has delivered platforms and cloud-native architectures built for real-world complexity. I would like to thank Kent & Cynthia Pamintuan, Allan, Betchay & Kent Sampang, Alexis Gruet, Yaron Lavi, Stefan Nagey, Rea Bustos, Mamen, Doc Alvin Macapinlac, Doc Sese, pp Don, pp Jun, Berna n Daphne, KapJ, Jetmel, Lhane, Aris. Also to my friends who have been constantly encouraging me: Kris, Migs, Dianne, Lau, Arnell & Axzel Matic, Migoy, Murali, Mark, Eva and Andre Bellaire, Takdol, Pow, Muy, Ariz, Kervin and Debbie, Mamisu, JCabading, Jonas. To my mates at Deel: Anton, Adi, Carpes, Clarissa, Remi, Bruno, Eli, Gal, Mor, Rene, Capi & Rocky, Felix, Harel, Jon, Andre, Phil, Raunaq, Slavic, Elia, Avi, Eithan, Chloe, Abhi, Albert, David, Aviv, Aaron, Kaleigh, Alex, Nadine, and Radhika.
Page
7
About the reviewers Matthew Setter is a PHP, Go, and Rust developer, developer educator, and podcaster. He's also the author of Mezzio Essentials and Deploy with Docker Compose. Roberto Butti is an open-source contributor, technical author, and international conference speaker. As a Senior Solutions Engineer at Storyblok, a leading headless CMS platform, he helps organizations build scalable and modern digital experiences. Passionate about sharing knowledge, Roberto maintains and contributes to open-source projects across the PHP, JavaScript, Laravel, and modern web technology ecosystems. His talks have been featured at developer conferences throughout Europe, where he shares practical insights on software architecture, developer productivity, performance, AI, and emerging technologies. Through books, articles, and community involvement, he promotes continuous learning and the collaborative spirit of open source.
Page
8
Table of Contents Preface xi Reviews ..................................................................................................................................... 0 Free benefits with your book ................................................................................................. xvii Chapter 1: Building a Foundation 1 Technical requirements ............................................................................................................. 2 PHP 8 installation considerations ............................................................................................. 2 Compiling PHP directly from source • 2 Installing PHP from community sources • 4 Installing ZendPHP • 5 Using Podman to define a containerized development environment ........................................ 8 Using GenAI to build a postcode database ............................................................................... 14 Using Composer for autoloading ............................................................................................. 28 Using AI to create a PHP 7 to PHP 8 code converter ................................................................. 33 Chapter 2: Using PHP 8 High Performance Features 41 Using a generator to speed up large file iteration .................................................................... 41 There's more… • 48 Using the recursive directory iterator ...................................................................................... 48 Using OPcache to boost performance ...................................................................................... 54 Taking the next step with JIT ................................................................................................. 60 There's more… • 64 Chapter 3: Working with PHP Functional Programming 65 Using GenAI prompts to develop PHP data validation functions ............................................. 66 Hinting at data types to improve AI code generation accuracy ................................................ 76 Searching multi-dimensional arrays using array_find ............................................................ 84 Making decisions using match expressions ............................................................................. 89
Page
9
Chapter 4: Working with PHP Object-Oriented Programming 95 Using focused GenAI prompts to build a simple OOP appointment calendar .......................... 95 Using the Symfony AI Bundle to build a GenAI-based service ................................................. 112 Developing a practical class hierarchy .................................................................................... 125 There's more... • 135 Creating a service container ................................................................................................... 135 Using lazy objects to improve performance ............................................................................ 139 Chapter 5: Interacting with a Database 147 Technical requirements .......................................................................................................... 147 Defining a factory class to produce a PDO database connection ............................................ 148 Using AI agents to define database entity classes ................................................................... 153 Creating an SQL query builder ............................................................................................... 157 Using a database to cache GenAI queries ............................................................................... 166 Chapter 6: Building Scalable Forms 177 Technical requirements ......................................................................................................... 178 Creating a generic form element generator ........................................................................... 178 There's more... • 186 Enhancing form generation using AI suggestions ................................................................. 186 There's more… • 189 Creating an HTML radio element generator .......................................................................... 189 Creating an HTML select element generator ......................................................................... 194 Implementing a form factory ................................................................................................ 199 There's more… • 204 Chaining filters ..................................................................................................................... 205 Chaining validators ................................................................................................................ 212 AI-driven dynamic form systems .......................................................................................... 219 Chapter 7: Making AI-Assisted Web Services and WebSockets Requests 223 Technical requirements ......................................................................................................... 224 Using standard I/O and PHP cURL to issue REST requests ..................................................... 224 Creating a middleware-based microservices REST service .................................................... 233 Table of Contents viii
Page
10
Tracking GenAI token usage .................................................................................................. 246 Building an AI-assisted real-time chat service using asynchronous PHP WebSockets ........... 253 Chapter 8: Working with Date/Time and International Aspects 277 Technical requirements ......................................................................................................... 278 Using emoticons or emojis .................................................................................................... 278 Handling DateTime errors ..................................................................................................... 281 Getting the locale from the browser data .............................................................................. 283 Formatting numbers by locale .............................................................................................. 288 Handling currency by locale .................................................................................................. 291 Formatting date/time by locale ............................................................................................. 293 Working with `str*` family differences on international websites ...................................... 297 Handling translations without Gettext ................................................................................. 299 Chapter 9: Implementing Test-Driven Development in a Feature 307 User acceptance criteria definition through AI and Gherkin ................................................. 307 Generating intentionally failing automated tests through AI ................................................ 309 Building solution code ........................................................................................................... 311 Scaling for complex behaviors ................................................................................................ 313 Building on top of the solution without breaking existing code ............................................. 321 Chapter 10: Looking at Advanced Algorithms 331 Technical requirements .......................................................................................................... 331 Using getters and setters ....................................................................................................... 332 There's more… • 342 Implementing a linked list .................................................................................................... 343 There's more… • 352 Converting your application to a decoupled plugin architecture .......................................... 353 Implementing a stack ............................................................................................................ 358 Building a binary search class ............................................................................................... 365 There's more… • 375 Implementing a search engine .............................................................................................. 375 Displaying a multidimensional array and accumulating totals ............................................. 386 There's more… • 391 ix Table of Contents
Page
11
Chapter 11: Implementing Software Design Patterns 393 Technical requirements ......................................................................................................... 394 Creational design patterns .................................................................................................... 394 There's more… • 401 Structural design patterns .................................................................................................... 402 There's more… • 406 Behavioral design patterns ................................................................................................... 406 There's more… • 411 Chapter 12: Improving Web Security 413 Technical requirements .......................................................................................................... 413 Safeguarding the PHP session ............................................................................................... 414 Securing forms with a token .................................................................................................. 417 Building a secure password generator .................................................................................... 421 Safeguarding forms with CAPTCHA ...................................................................................... 432 Using AI to develop an encryption and decryption solution .................................................. 439 Chapter 13: Unlock the Code Bundle and the PDF Version 447 Unlock this book's free benefits in three easy steps ............................................................... 448 Other Books You May Enjoy 452 Index 455 Table of Contents x
Page
12
Preface The AI genie is out of the bottle and there's no putting it back. AI-assisted development is rapidly becoming the de facto way of life for developers, and PHP developers are eager to embrace it. This cookbook-style book gives you invaluable advice and solid, practical, real- world code examples known as "recipes" that illustrate not only how AI can boost PHP programming, but also how AI can be used to enhance PHP-based websites. Join us and ride the wave of PHP programming in the AI era. Who this book is for This book targets PHP developers from beginner to advanced levels. Coverage spans environment setup, performance optimization, functional programming, OOP, database integration, web forms, REST APIs, test-driven development, algorithms, design patterns, and security—making it suitable for any PHP developer looking to modernize skills with PHP 8 and AI-assisted workflows. What this book covers Chapter 1, Building a Foundation, establishes a modern PHP 8 development baseline covering multiple installation methods, containerized environments using Podman, Composer autoloading, strict typing, static analysis, coding standards enforcement, and AI-assisted code generation using GenAI tools. Chapter 2, Using PHP 8 High Performance Features, examines PHP 8 performance optimization through Generators providing memory-efficient large file iteration, easy directory traversal using the SPL's RecursiveDirectoryIterator, OPcache for bytecode caching, and the Just-In- Time (JIT) compiler for machine code generation and execution speed improvements. Chapter 3, Working with PHP Functional Programming, explores PHP functional programming through AI-assisted data validation function development, improving GenAI code generation accuracy through type hinting, multi-dimensional array searches using PHP 8.5's new array_find() function, and match expressions that streamline decision-making logic. Chapter 4, Working with PHP Object-Oriented Programming, presents practical OOP recipes using PHP 8, including building an AI-prompted appointment calendar system, integrating the Symfony AI Bundle, implementing PSR-11 service containers, designing class hierarchies, and using PHP 8.5 lazy objects to reduce memory consumption.
Page
13
Chapter 5, Interacting with a Database, covers practical PHP database integration techniques: building a PDO connection factory via a PSR-11 service container, using AI agents to generate entity classes from SQL definitions, creating a flexible SQL query builder using the Builder pattern, and caching GenAI API responses in a PSR-16-compliant database cache. Chapter 6, Building Scalable Forms, introduces building reusable form components in PHP: a generic element generator, separate renderers for each input type, a form factory, and chained filters and validators, with optional AI help for suggesting fields. Chapter 7, Making AI-Assisted Web Services and WebSockets Requests, presents recipes for issuing REST requests using PHP Streams and cURL, building a middleware-based microservices REST service, tracking GenAI API token usage to help control costs, and implementing real-time asynchronous communication using WebSockets for an AI-assisted chat service. Chapter 8, Working with Date/Time and International Aspects, covers internationalization in PHP: emoji handling, locale detection, locale-aware number, currency and date formatting, multibyte strings, and simple JSON-based translations. Chapter 9, Implementing Test-Driven Development in a Feature, shows how to build a feature test- first: write acceptance criteria in Gherkin, use AI to generate failing PHPUnit tests, add code until they pass, then grow the suite with Behat. Chapter 10, Looking at Advanced Algorithms, works through common algorithms and data structures in PHP 8: getters and setters, linked lists, stacks, binary search, a plugin architecture, a search engine, and displaying nested arrays with totals. Chapter 11, Implementing Software Design Patterns, introduces creational, structural, and behavioral patterns in PHP, including the Factory, Adapter, and State patterns, and explains when each one is a good fit. Chapter 12, Improving Web Security, includes practical security recipes for PHP: securing sessions, adding CSRF tokens, generating strong passwords, adding CAPTCHA, and building an AES-256-GCM encryption helper with help from Claude Code. To get the most out of this book Readers need basic PHP knowledge and command-line familiarity, with chapters progressively requiring stronger OOP skills, SQL, HTTP concepts, and testing experience. Later chapters build on earlier setups and concepts. Access to a GenAI platform and the containerized development environment established in Chapter 1 are assumed throughout. Preface xii
Page
14
Software/Hardware covered in the book OS Requirements Podman Windows, Mac OS X, and Linux (any) GenAI access Windows, Mac OS X, and Linux (any) A code editor or IDE Windows, Mac OS X, and Linux (any) Google reCAPTCHA account None Claude (desktop, Claude.ai, or Claude Code), OpenAI API key (optional) Windows, Mac OS X, and Linux (any) PHP 8.5+, nginx, MariaDB, Composer, Adminer (database manager), OpenSSL extension, PHPUnit and Behat Available in the Podman container you will build for the book If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (check next section). Doing so will help you avoid any potential errors related to the copying and pasting of code. Download the example code files This book includes a complete downloadable code bundle containing all the example projects and files used throughout the chapters. We recommend downloading the bundle so you can follow along smoothly and experiment with the examples. Use the bundle as a practical starting point. Modify it, extend it, and apply what you learn by creating your own variations as you progress through the chapters. Get the code bundle If you bought the book directly from Packt: Go to packtpub.com Click your profile picture and select Your Orders Find this book and click Download Code If you bought this book from Amazon or any other channel partner: Go to packtpub.com/unlock or scan the following QR code: 1. 2. 3. 1. xiii Preface
Page
15
Search for this book Sign up or log in to your free Packt account Upload your proof of purchase and download the code bundle locally Usage note: You're free to use and modify this code for personal learning and non-commercial projects. Conventions used There are a number of text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm‑10*.dmg disk image file as another disk in your system." A block of code is set as follows: GENAI_URL=https://api.openai.com/v1/responses GENAI_MODEL=gpt-4.1-nano GENAI_API_KEY=put_your_API_key_here GENAI_BRIDGE=OpenAi When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: GENAI_URL=https://api.openai.com/v1/responses GENAI_MODEL=gpt-4.1-nano GENAI_API_KEY=put_your_API_key_here GENAI_BRIDGE=OpenAi Any command-line input or output is written as follows: php composer.phar require symfony/ai-scraper-tool --ignore-platform-reqs php composer.phar require symfony/ai-agent --ignore-platform-reqs 2. 3. 4. Preface xiv
Page
16
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel." Sections In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also). To give clear instructions on how to complete a recipe, use these sections as follows: Getting ready This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe. How to do it… This section contains the steps required to follow the recipe. How it works… This section usually consists of a detailed explanation of what happened in the previous section. There's more… This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe. See also This section provides helpful links to other useful information for the recipe. Get in touch Feedback from our readers is always welcome. General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com. Tips or important notes Appear like this. Note xv Preface
Page
17
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details. Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about Packt, please visit packt.com. Preface xvi
Page
18
Free benefits with your book This book includes free benefits designed to support your learning and help you apply what you learn effectively. Activate them now for instant access (see the How to unlock section for instructions). Here's a quick overview of what you can instantly unlock with your purchase: xvii Preface
Page
19
How to unlock Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page. Note: Have your invoice handy. Purchases made directly from the Packt website don't require an invoice. Preface xviii
Page
20
1 Building a Foundation This chapter establishes a modern PHP development baseline, covering PHP 8 installation, containerized environments, and Composer autoloading, while introducing strict typing, static analysis, and coding standards enforcement. Given the advanced AI coding tools available today, building a solid foundation ensures structural consistency and maintainability, supporting both human developers and AI-assisted workflows throughout every subsequent recipe in the book. Here we have a look at a number of old and new ways that you can install PHP 8. We also have a look at the concept of containerizationidx_59774ce2 featuring Podman, a fully open-source and free tool that follows Docker syntax and shows you how to set up a complete PHP development environment in which you can experiment with the recipes covered in this book. We also have a look at howidx_cdd6e763 advances in Generative AI (GenAI) can be used as a tool to boost code development. The nextidx_f558bcde recipe shows you how to use Composer, a popular PHP-based package management system, to facilitate the autoloading process. Finally, we have a look at using GenAI to create a PHP 7 to PHP 8 conversion tool. In this chapter, we will cover the following recipes: PHP 8 installation considerations Using Podman to define a containerized development environment Using GenAI to build a postcode database Using Composer for autoloading Using AI to create a PHP 7 to PHP 8 code converter • • • • •