Modernizing Legacy Applications in PHP
eBook - ePub

Modernizing Legacy Applications in PHP

Paul M. Jones

Compartir libro
  1. 286 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Modernizing Legacy Applications in PHP

Paul M. Jones

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Get your code under control in a series of small, specific steps

About This Book

  • Learn to extract and replace legacy artifacts,
  • Improve your application from the ground up while keeping your codebase fully operational,
  • Improve the quality of your legacy applications.

Who This Book Is For

PHP developers from all skill levels will be able to get value from this book and will be able to transform their spaghetti code applications to clean, modular applications. If you are in the midst of a legacy refactor or you find yourself in a state of despair caused by the code you have inherited, this is the book for you. All you need is to have PHP 5.0 installed, and you're all set to change the way you maintain and deploy your code!

What You Will Learn

  • Replace global and new with dependency injection
  • Extract SQL statements to gateways
  • Convert action logic to controllers
  • Remove repeated logic in page scripts
  • Create maintainable PHP code from crufty legacy PHP

In Detail

Have you noticed that your legacy PHP application is composed of page scripts placed directly in the document root of the web server? Or, do your page scripts, along with any other classes and functions, combine the concerns of model, view, and controller into the same scope? Is the majority of the logical flow incorporated as include files and global functions rather than class methods? Working with such a legacy application feels like dragging your feet through mud, doesn't it?This book will show you how to modernize your application in terms of practice and technique, rather than in terms of using tools like frameworks and libraries, by extracting and replacing its legacy artifacts. We will use a step-by-step approach, moving slowly and methodically, to improve your application from the ground up. We'll show you how dependency injection can replace both the new and global dependencies. We'll also show you how to change the presentation logic to view files and the action logic to a controller. Moreover, we'll keep your application running the whole time. Each completed step in the process will keep your codebase fully operational with higher quality. When we are done, you will be able to breeze through your code like the wind. Your code will be autoloaded, dependency-injected, unit-tested, layer-separated, and front-controlled. Most of the very limited code we will add to your application is specific to this book. We will be improving ourselves as programmers, as well as improving the quality of our legacy application.

Style and approach

This book gives developers an easy-to-follow, practical and powerful process to bring their applications up to a modern baseline. Each step in the book is practical, self-contained and moves you closer to the end goal you seek: maintainable code. As you follow the exercises in the book, the author almost anticipates your questions and you will have the answers, ready to be implemented on your project.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Modernizing Legacy Applications in PHP un PDF/ePUB en línea?
Sí, puedes acceder a Modernizing Legacy Applications in PHP de Paul M. Jones en formato PDF o ePUB, así como a otros libros populares de Ciencia de la computación y Programación en PHP. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2016
ISBN
9781787127784

Modernizing Legacy Applications in PHP


Table of Contents

Modernizing Legacy Applications in PHP
Credits
Foreword
About the Author
Acknowledgement
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
1. Legacy Applications
The typical PHP application
File Structure
Page Scripts
Rewrite or Refactor?
The Pros and Cons of Rewriting
Why Don't Rewrites Work?
The Context-switching problem
The Knowledge problem
The Schedule Problem
Iterative Refactoring
Legacy Frameworks
Framework-based Legacy Applications
Refactoring to a Framework
Review and next steps
2. Prerequisites
Revision control
PHP version
Editor/IDE
Style Guide
Test suite
Review and next steps
3. Implement an Autoloader
PSR-0
A Single Location for Classes
Add Autoloader Code
As a Global Function
As a Closure
As a Static or Instance method
Using The __autoload() Function
Autoloader Priority
Common Questions
What If I Already Have An Autoloader?
What are the Performance Implications Of Autoloading?
How Do Class Names Map To File Names?
Review and next steps
4. Consolidate Classes and Functions
Consolidate Class Files
Find a candidate include
Move the class file
Remove the related include calls
Spot check the codebase
Commit, Push, Notify QA
Do ... While
Consolidate functions into class files
Find a candidate include
Convert the function file to a class file
Change function calls to static method calls
Spot check the static method calls
Move the class file
Do ... While
Common Questions
Should we remove the autoloader include call?
How should we pick files for candidate include calls?
What if an include defines more than one class?
What if the one-class-per-file rule is disagreeable?
What if a Class or Function is defined inline?
What if a definition file also executes logic?
What if two classes have the same name?
What about third-party libraries?
What about system-wide libraries?
For functions, can we use instance methods instead of static methods?
Can we automate this process?
Review and next steps
5. Replace global With Dependency Injection
Global Dependencies
The replacement process
Find a global variable
Convert global variables to properties
Spot check the class
Convert global properties to constructor parameters
Convert instantiations to use parameters
Spot check, Commit, Push, Notify QA
Do ... While
Common Questions
What if we find a global in a static method?
Is there an alternative conversion process?
What about class names in variables?
What about superglobals?
What about $GLOBALS?
Review and next steps
6. Replace new with Dependency Injection
Embedded instantiation
The replacement process
Find a new keyword
Extract One-Time creation to dependency injection
Extract repeated creation to factory
Change instantiation calls
Spot Check, Commit, Push, Notify QA
Do ... While
Common Questions
What About Exceptions and SPL Classes?
What about Intermediary Dependencies?
Isn't this a lot of code?
Should a factory create collections?
Can we automate all these Injections?
Review and next steps
7. Write Tests
Fighting test resistance
The way of Testivus
Setting up a test suite
Install PHPUnit
Create a tests/ directory
Pick a class to test
Write a test case
Do ... While
Common Questions
Can we skip this step and do it later?
Come On, Really, Can We Do This Later?
What about hard-to-test classes?
What about our earlier characterization tests?
Should we test private and protected methods?
Can we change a test after we write it?
Do we need to test Third-party libraries?
What about code coverage?
Review and next steps
8. Extract SQL statements to Gateways
Embedded SQL Statements
The extraction process
Search for SQL statements
Move SQL to a Gateway class
Namespace and Class names
Method names
An initial Gateway class method
Defeating SQL Injection
Write a test
Replace the original code
Test, Commit, Push, Notify QA
Do ... While
Common Questions
What about INSERT, UPDATE, and DELETE Statements?
What about Repetitive SQL strings?
What about complex query strings?
What about queries inside non-Gateway classes?
Can we extend from a base Gateway class?
What about multiple queries and complex result structures?
What if there is no Database Class?
Review and next steps
9. Extract Domain Logic to Transactions
Embedded Domain Logic
Domain logic patterns
The Extraction Process
Search for uses of Gateway
Discover and Extract Relevant Domain Logic
Example Extraction
Spot check the remaining original code
Write tests for the extracted transactions
Spot check again, Commit, Push, Notify QA
Do ... While
Common Questions
Are we talking about SQL transactions?
What about repeated Domain Logic?
Are printing and echoing part of Domain Logic?
Can a transaction be a class instead of a Method?
What about Domain Logic in Gateway classes?
What about Domain logic embedded in Non-Domain classes?
Review and next steps
10. Extract Presentation Logic to View Files
Embedded presentation logic
The Extraction process
Search for Embedded presentation logic
Rearrange the Page script and Spot Check
Extract Presentation to View file and Spot Check
Create a views/ Directory
Pick a View File name
Move Presentation Block to View file
Add Proper Escaping
Write View File Tests
The tests/views/ directory
Writing a View File Test
Asserting Correctness Of Content
Commit, Push, Notify QA
Do ... While
Common Questions
What about Headers and Cookies?
What if we already have a Template system?
What about Streaming Content?
What if we have lots of Presentation variables?
What about class methods that generate output?
What about Business Logic Mixed into the presentation?
What if a page contains only presentation logic?
Review and next steps
11. Extract Action Logic to Controllers
Embedded action logic
The Extraction Process
Search for Embedded Action Logic
Rearrange the Page Script and Spot Check
Identify Code Blocks
Move Code to Its Related Block
Spot Check the Rearranged Code
Extract a Controller Class
Pick a Class Name
Create a Skeleton Class File
Move the Action Logic and Spot Check
Convert Controller to Dependency Injection and Spot Check
Write a Controller Test
Commit, Push, Notify QA
Do ... While
Common Questions
Can we pass parameters to the Controller method?
Can a Controller have Multiple actions?
What If the Controller contains include Calls?
Review and next steps
12. Replace Includes in Classes
Embedded include Calls
The Replacement process
Search for include Calls
Replacing a Single include Call
Replacing Multiple include Calls
Copy include file to Class Method
Replace the original include Call
Discover coupled variables through testing
Replace other include Calls and Test
Delete the include file and test
Write a test and refactor
Convert to Dependency Injection and test
Commit, Push, Notify QA
Do ... While
Common QuestionsCan one class receive logic from many include files?
What about include calls originating in non-class files?
Review and next steps
13. Separate Public and Non-Public Resources
Intermingled resources
The separation process
Coordinate with operations personnel
Create a document root directory
Reconfigure the server
Move public resources
Commit, push, coordinate
Common Questions
Is This Really Necessary?
Review and next steps
14. Decouple URL Paths from File Paths
Coupled Paths
The Decoupling Process
Coordinate with Operations
Add a Front Controller
Create a pages/ Directory
Reconfigure the Server
Spot check
Move Page scripts
Commit, Push, Coordinate
Common Questions
Did we really Decouple the Paths?
Review and next steps
15...

Índice