35,18 €
A PHP developer's practical guide to planning, writing, and deploying maintainable and extensible software solutions with automated tests in a well-structured way
Key Features
Learn to organize and translate business requirements into maintainable softwareMinimize regressions and bugs while releasing new features or bug fixesBuild maintainable applications using SOLID principles
Book Description
PHP web developers end up building complex enterprise projects without prior experience in test-driven and behavior-driven development which results in software that's complex and difficult to maintain. This step-by-step guide helps you manage the complexities of large-scale web applications. It takes you through the processes of working on a project, starting from understanding business requirements and translating them into actual maintainable software, to automated deployments.
You'll learn how to break down business requirements into workable and actionable lists using Jira. Using those organized lists of business requirements, you'll understand how to implement behavior-driven development (BDD) and test-driven development (TDD) to start writing maintainable PHP code. You'll explore how to use the automated tests to help you stop introducing regressions to an application each time you release code by using continuous integration.
By the end of this book, you'll have learned how to start a PHP project, break down the requirements, build test scenarios and automated tests, and write more testable and maintainable PHP code. By learning these processes, you'll be able to develop more maintainable, and reliable enterprise PHP applications.
What you will learn
Understand how to start a software projectDiscover how to use Jira as a tool to organize your tasksExplore when and how to write unit, integration, and functional tests using PHPUnitWrite behavior-driven tests using BehatApply SOLID principles to help you write more testable codeGet the most out of your automated tests by using continuous integrationUse continuous delivery to help you prepare your application for deployment
Who this book is for
This book is for PHP software developers looking to implement TDD and BDD in their projects. An understanding of object-oriented programming is required to get the most out of this book. Professional software development experience will also be beneficial to understand real-life business cases.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 270
Veröffentlichungsjahr: 2023
Build extensible, reliable, and maintainable enterprise-level applications using TDD and BDD with PHP
Rainier Sarabia
BIRMINGHAM—MUMBAI
Copyright © 2023 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.
Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Bhavya Rao
Senior Editor: Mark D’Souza
Senior Content Development Editor: Rakhi Patel
Technical Editor: Simran Udasi
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Manju Arasan
Production Designer: Roshan Kawale
Marketing Coordinator: Anamika Singh
First published: January 2023
Production reference: 1161222
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80323-075-7
www.packt.com
In the memory of my aunt Rose, who raised me, and to my family and friends. To Eva, for the unending encouragement. To my partner, Frezel Enriquez, for the love and support throughout my journey in life.
– Rainier Sarabia
I have known and worked with Rainier Sarabia for more than 5 years. In this book, Test-Driven Development with PHP 8, Rainier takes you on a learning journey that started in the late 1990s, with not only PHP but test-driven development itself. For more than 20 years, PHP has continued to evolve to meet the needs of developers around the world. In parallel, test-driven development and agile principles have also evolved, culminating in this book combining all three to demonstrate how easily an application with frameworks, environments, and toolchains can be built rapidly, and more importantly, with rock-solid reliability.
In his presentations and examples, Rainier shows how easy it is not only to create consistently tested applications but to have consistent environments to run those tests in, no matter whether they are on your machine, a fellow developer’s machine, a cloud-based CI, or in a test environment.
With Test-Driven Development with PHP 8, you’ll learn the best practices for writing reliable, maintainable code with PHP’s object-oriented architecture. After you complete Rainier’s book, you’ll understand how to take full advantage of test-driven development in PHP.
Beyond developing apps, you’ll learn how to quickly and easily bootstrap applications in cloud services using containerized environments, giving transportability and consistency to your application.
Rainier encapsulates the knowledge gained through years as a world-class software engineer and passionate advocate. With his words, step-by-step instructions, screenshots, source code snippets, examples, and links to additional sources of information, you will learn how to continuously enhance your skills and applications.
Ben Hansen
Directory of Quality Assurance, PayGroup Ltd.
Rainier Sarabia is a Software Engineering Manager, who currently works in Melbourne, Australia for Astute Payroll, a Deel company. He has worked on hundreds of complex software projects, including massive enterprise SaaS products while leading and training senior engineers from all over the world. His favorite programming languages are PHP, C#, Java, and Javascript which he uses for both professional and personal projects. He co-founded his first tech company back in 2014, with over 400,000 users. Outside of working hours, he is an amateur astronomer. He spends most of his time doing astrophotography focusing on deep-sky objects like nebulae and galaxies.
I want to thank the people who have been inspiring me and helping me in writing this book. I’d like to thank Eva Bellaire, Ilia Mogilevsky, and Ben Hansen for spending so much of their free time and weekends helping me with this book, I really appreciate it.
To the Packt team: Manthan Patel, Rakhi Patel, Mark D’Souza, Bhavya Rao, thank you so much for your patience and guidance, I’ve learned so much from you!
My mates from Exsentriks: Jan Albee Angeles, Joms Calma, Blink Easley, Randy Porcioncula, Vincent Rafols, William Dela Pena, and Richard Coles, thanks so much for the support and ideas I always love and enjoy our C#, PHP, Java, and Javascript discussions!
For the past 6 years, Astute Payroll, and PayGroup have been very supportive of me and my ideas! To Luke Zawadzki, thank you so much for all the help and guidance, mate! I’d also like to thank, Eloise Roberts, Sally Laycock, Mahin Sonia, Johnny Yu, Trang Dinh, Adi Setiono, Tadek Chavez, Marcus Webb, Shelley Mackie, Nicole Poulton, Adam Perks, Paul Radford, Rudy Compayan, Joyce Orevillo, Tao Ding, Tim Evetts, Julian Calaby, Mac Wilgucki, Tim Malone, Ginli Chew, Mitch Collins, Trish Scally, and Rick Measham. And I’d also like to thank Adam Parrish, Andrew Sekula, and Vik Radha for the great table tennis battles we had in MIM! Lastly, I also want to thank Erin Jan Gandia, Oleg Posternatsky, Matteo Bortolu, Dexter Naag, and Andre Bellaire for all the support.
About the reviewers
Ben Hansen has been a QA professional his entire IT career, starting as a purely manual tester, then learning and working up to automation testing, QA lead, and now QA director overseeing large international teams. Specializing in various CRM, accounting, and payroll applications, he has pioneered many testing techniques and technologies, reducing testing times from months to weeks for features in some applications while increasing quality.
Eva Bellaire is a CPA-qualified leader who has worked in multiple positions in accounting and project delivery with both agile and waterfall methods. Her experience includes management and oversight of projects for organizations in a diverse set of industries including mining and engineering, professional services, higher education, and financial services. She is experienced in enterprise transformation and technology enablement across finance, planning, payroll, HR, and analytics software. She has a passion for continuous learning as well as mentoring and people development.
Ilia Mogilevsky is a Ukrainian-born Jewish immigrant who is currently leaving in Melbourne, Australia, with his beautiful wife, two young inquisitive children, and his always playful golden retriever, Daisy. He is an industry-certified professional with over 20 years of full-time commercial experience as a code wrangler, technical lead, solutions architect, and engineering manager. Ilia has worked in various areas of software engineering, ranging from big digital agencies such as Next Digital, massive B2B and B2C companies such as Hanes Australasia (Bonds, Sheridan, Berlei, Champion), and small start-ups such as Combitel, where he helped develop a data-driven web-based application for IPTV streaming. As of 2022, he is currently employed at SmartBear as an engineering manager, working with the PactFlow team to help engineers all over the world build more robust testable software. In recent years, he turned his passion for technology with a wide breadth of software engineering knowledge, skills, and experiences to helping businesses achieve their critical goals by building successful technology-centric teams and continuously cultivating his growth mindset while helping and supporting his peers through mentoring, coaching, and best practices.
In his spare time, he loves to travel with his family and has become a keen landscape photographer.
For the past few years, I’ve been helping friends and colleagues learn more about PHP and Test-Driven Development (TDD). I realized that I found myself repeating some of the things I’m discussing with different people. I told myself, it would be great if I could just point my friends and colleagues to a collection of my notes so that I could help them with developing applications in PHP from the start of the project, up to deployment. Unfortunately, my notes only made sense to me.
In 2009, I was working as a C# developer and made friends with my colleagues who were fellow programming enthusiasts. Unfortunately, we haven’t been in touch for a long time. 11 years later, in 2020 while in COVID lockdown, I got in touch with my long-lost friends, and we started chatting about programming. They told me that they were very keen on learning about TDD with PHP. We then did a screen-sharing tutorial session on a weekend, and I realized that I seriously needed to start writing something a bit more organized to help other people who are interested in learning about this topic.
I do self-training most of the time. I buy books, read them, and watch tutorials about things I want to learn myself. I then decided to write a book about TDD with PHP. Since I have learned a lot from the books published by Packt, I thought I should reach out to them.
Reading this book will help you start organizing your thoughts and the things you need to build for a project as a software developer. You will learn how to write and use automated tests to help improve the quality of the software you produce, and you will also learn how to use tools to automate the execution of your tests, as well as the deployment of your code onto remote servers. I’m aiming for the reader to understand the value of TDD as a process, and not just learn about writing automated tests. That’s why I have covered topics from starting a project to deploying it on a public-facing server.
If you’re a professional PHP developer who’s getting tired of working on applications that are not easily testable or maintainable, this book will help you be a better professional PHP developer. You will learn how to utilize Test-Driven Development (TDD) and Behaviour-Driven Development (BDD) to help you produce more structured and maintainable software.
Chapter 1, What is Test-Driven Development and Why Use it in PHP?, Goes through the definition of TDD, what problem it tries to solve, what are the benefits of PHP and what we developers will get from implementing it. This chapter will also make you understand the value of TDD in large projects and how it helps reduce regressions.
Chapter 2, Understanding and Organizing the Business Requirements of Our Project, explains how to interpret business requirements into an organized list. The list can be used to help developers prioritize and determine what features we need to build, and which features we need to build first.
Chapter 3, Setting Up Our Development Environment Using Docker Containers, is all about Docker containers for development. Using containers will help developers get more consistent application setups in different server environments.
Chapter 4, Using Object-Oriented Programming in PHP, goes through the Object-Oriented Programming (OOP) concept in PHP. Understanding OOP in PHP is crucial for implementing TDD, and BDD.
Chapter 5, Unit Testing, covers the basics of unit testing. The lessons learned in this chapter will be the foundations for the concepts that will be discussed in applying TDD and BDD in the following chapters.
Chapter 6, Applying Behavior-Driven Development, provides an introduction to the process of BDD. The BDD process will help software developers ensure that the expected behavior of a software product is achieved.
Chapter 7, Building Solution Code with BDD and TDD, demonstrates how to use BDD and TDD together. Implementing BDD and TDD together will help ensure that the expected behavior is delivered, and it will also help increase the reliability of the software being produced.
Chapter 8, Using TDD with SOLID Principles, involves following the SOLID principles in a project. This will help developers implement the SOLID principles while following TDD in a more realistic use scenario.
Chapter 9, Continuous Integration, details Continous Integration (CI) for test execution. CI is used to help merge reliable code to the master branch of a project by making sure that all automated tests pass first.
Chapter 10, Continuous Delivery, discusses using Continuous Delivery (CD) to automate the release process. Going further than CI, we will automate the deployment process of the product.
Chapter 11, Monitoring, unpacks how to use monitoring tools for deployed applications. Applications running in production will need to be maintained and having monitoring tools help developers to get on top of possible issues in production.
The instructions in the book are Unix based. The development machine used as an example host machine in the book runs on MacOS 12.3 and should work on later versions as well. However, the Docker containers should also run on Windows and Linux machines.
Software/hardware covered in the book
Operating system requirements
Docker
macOS, Linux, or Windows
PHP 8.1
Linux
MySQL 8
Linux
PHPStorm
macOS, Linux, or Windows
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Test-Driven-Development-with-PHP-8. If there's an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/BwjU3.
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: “The test class name needs to be suffixed with Test, and it extends the PHPUnit\Framework\TestCase class.”
A block of code is set as follows:
<?php namespace App\Validator; use App\Model\ToyCar; use App\Model\ValidationModel; interface ToyCarValidatorInterface { public function validate(ToyCar $toyCar): ValidationModel;Any command-line input or output is written as follows:
$ cd docker $ docker-compose build && docker-compose up -dBold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Paste the script into the text area and click on the Commit File button.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
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 and fill in the form.
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 [email protected] 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.
Once you’ve read Test-Driven Development with PHP 8, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/978-1-80323-075-7
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyIn this part of the book, you will learn the concepts of test-driven development and object-oriented programming in PHP, interpret business requirements as an actionable list, and set up development environments using Docker containers.
This section comprises the following chapters:
Chapter 1, What Is Test-Driven Development and Why Use It in PHP?Chapter 2, Understanding and Organizing the Business Requirements of Our ProjectChapter 3, Setting Up Our Development Environment Using Docker ContainersChapter 4, Using Object-Oriented Programming in PHPDeveloping web applications is fun and productive when using the PHP programming language. The learning curve to get started with PHP is relatively shallow, which is a very important trait of a programming language. There are a lot of open source learning materials, frameworks, packages, and full-blown extendable products backed by a very large open source community available for PHP developers. PHP is an enterprise-ready programming language and is widely used as a web-based solution to solve different business problems. Businesses and developers can quickly develop and deploy web applications with PHP. Once these businesses start to succeed and grow, they’ll need more features, bug fixes, and improvements to be released on top of the original solution. This is where it starts to get interesting. Maintenance of commercially successful software can be one of the biggest contributing factors to the cost of the software, especially when it’s not built to be easily maintainable or testable from the beginning. Implementing test-driven development (TDD) will improve the maintainability of the software and will help reduce the cost and time to market for a feature.
There’s a problem that most of us developers might have already experienced or observed: a feature or a bug fix has been released and it has caused more problems, regressions, or unintended software behavior. If you are coming from a development environment where most or all the quality assurance (QA) tests are done manually post-, pre-, or even mid-development, then you might have experienced the issues that I have mentioned. This is where implementing TDD can really help. TDD not only helps in implementing automated tests but also guides or even forces us in a way to develop cleaner and more loosely coupled codes. TDD helps developers write and build tests before even writing a single feature code – this helps ensure that whenever a feature or solution code is being written, there will be a corresponding test already written for it. It also helps us developers stop saying “I’ll add my unit tests later.”
Before writing any codes, it’s very important to understand what TDD is, and what it is not. There are some common misconceptions about TDD that we need to clear up to help us stay focused on what TDD really is. In this chapter, we will also try to use a very simple analogy and try to emphasize why we would want to implement TDD as a part of a software project.
In this chapter, we will be covering the following:
What is TDD?Common misconceptions about TDDWhy should we even consider TDD?What are we planning to achieve in this book?TDD is a simple way of developing software where we think about and define what needs to be the outcome of our programs before we start writing the actual codes that solve a problem.
TDD is a software development process where test cases are developed first before writing the actual code that solves a problem. The test cases will be written as PHP code that will use or call the solution code that developers will be building. The test case code that you build will trigger the development of the solution code that you will write to solve a problem.
From what I’ve seen, this literal description is what demotivates a lot of developers from applying this process. TDD is a process, and it’s a way of thinking. It’s not simply about writing unit tests.
The test program you write should always fail the first time you run it because you haven’t built the programs the test needs to pass yet. Then, you will basically have to build the solution codes that the test program will use until the test program itself gets the expected results from your solution codes. Literally, the failing test will drive you to write the codes to pass the test – hence the term TDD. Maybe you can even call it failing-TDD. It’s like saying “I wrote a test to fail my code, now I need to fix it.”
In TDD, I can see four main reasons why it’s important to write a failing test first. First, you will write a failing test and make sure your test framework application can recognize it. This ensures that your development environment is properly configured and you can run your test programs. Second, your failing test will help you define what solution or feature code you’d like to write, and what is expected for that test to pass. This will help you as a developer, in setting or focusing your mindset on the purpose of the feature code you are writing. Third, the failing tests you write will serve as reminders to know what other programs you need to complete. Fourth, writing your tests first will help ensure that your solution code is covered by automated tests.
By trying to make your solution code unit-testable, you are sometimes inadvertently making your codes less coupled – it’s like a cycle. As you continue to write loosely coupled codes, you will notice that your codes will start to look more organized and less of a tangled mess. As you continue writing solution code following the TDD process, it will continuously help you spot where tight couplings are in your product, sometimes encouraging you to refactor and decouple your code just to make it unit-testable. There are software development principles that will help you further improve your codes, such as the Single-Responsibility Principle, which will be discussed more in Chapter 8, Using TDD with SOLID Principles.
Now that we have defined and have a brief understanding of what TDD is, let’s go through some of the common misconceptions associated with it.
In this section, we’ll look at some of the misconceptions that I have personally observed that developers have about TDD. Time and time again, I’ve encountered people who have a poor understanding of TDD. When I talk to some of them about why they’re not a fan of TDD, they sometimes tell me reasons that are not even related to TDD.
I have said this myself. I used to think that I just needed to churn out solution code as fast as possible, test a little bit manually, and let the testing department ensure that everything is built correctly. This is probably the worst misconception I’ve ever had about TDD. As software developers, we develop software as solutions to problems. If we developers are the ones causing more problems, then we are not doing our jobs.
I would be surprised if this were the first time you are hearing this. I first heard this from a client who had a technical background, not from a developer. I wasn’t a fan of TDD myself and willingly agreed with my client back then. Sure, it’s slower to write test codes and solution codes together; I would have to type more characters on my keyboard, after all!
When working on enterprise projects, from what I have experienced, TDD is what saved us from months of bugs and regressions. Writing tests and having good test coverage, which is discussed in Chapter 5, Unit Testing, will help ensure that the next time someone else touches the code or adds new features, no regressions will be introduced. TDD will help you build a lot of automated tests, and running these tests is cheaper and quicker than handing over your untested solution code to a testing team or testing company for manual testing.
TDD is not about writing automated tests or unit tests for existing functionalities. TDD is not about getting your QA department or getting a third-party company to write automated tests for existing software. This is the exact opposite of TDD.
The most common misconception I have observed is that some developers and testers assume that TDD has something to do with testers writing automated tests for the codes that the developers build. I believe that this is a very bad misconception. It’s no different from developing a program and sending it to the QA department for manual testing.
Getting testers to write automated functional tests is a very good thing, especially for existing functionalities that do not have automated tests, but this should only be thought of as supplementary test coverage for software and not be confused with TDD.
The last misconception that I have encountered is assuming that if we developers have built excellent test coverage by following TDD, we will no longer need input from the software development department and QA department or team. Time and time again, I’ve proven myself wrong, believing that code that’s written via the TDD methodology is bulletproof. I am very fortunate to work with knowledgeable and skilled software engineers and test engineers. Code reviews are critical; always get your codes and test scenarios peer-reviewed. Edge-case tests and functional scenarios that the developers might have overlooked will cause problems – and in my experience, they have caused big problems.
It is very important for the development and testing teams to properly understand the functional and acceptance test cases so that all imaginable scenarios are covered: the different types of tests will be covered in Chapter 5, Unit Testing. This is where behavioral-driven development (BDD) will start to make sense; BDD will be discussed in more detail in Chapter 6, Applying Behaviour-Driven Development. I have worked with test engineers and QA personnel who can come up with edge cases that I couldn’t have imagined.
We have gone through some common misconceptions I have encountered about TDD. Now let’s try to make a case for why we’d want to consider using TDD in our development process.
Why would I want my codes to be driven by tests? I want my codes to be driven by requirements and happy clients! You may have heard about the term TDD and felt uncomfortable with it. When I first heard about the term TDD, I was a bit uncomfortable with it too. Why would you want to waste time writing test code to test solution code that doesn’t exist yet? Seriously, I need to write the actual code that solves the business problem, and you want me to write tests first? As a matter of fact, some developers I have trained and worked with have had this same question too – and it’s the exact same question that was stopping them from getting interested in TDD!
