So you recognize one thing about code refactoring, huh? However are you able to create a viable and scalable refactoring course of in your PHP software? Learn this intensive tutorial and get the perfect insights from a developer who refactors for a residing – from determining the system construction, via static code evaluation, to updating your libraries, and extra. The brand new December 2023 replace even consists of tips about use AI to enhance your skillset!
* The article was up to date on December sixth 2023 to mirror the most recent developments in PHP code refactoring in addition to the brand new experiences and ideas of the writer. Study extra in regards to the significance of correct naming conventions, extracting and using AI-powered instruments in code refactoring (will they take his job!? – learn on and discover out!).
In the middle of my profession as a PHP developer, I noticed and labored on a variety of PHP apps in want of refactoring. That they had all kinds of issues, however all of them stemmed from a short-sighted strategy to improvement. The very first thing to do to refactor them is to alter this strategy.
However what to do subsequent? In any case, every app is completely different. Whereas there isn’t a one-size-fits-all resolution, I’m going to give you the subsequent smartest thing within the type of sensible PHP refactoring suggestions primarily based on my on a regular basis expertise.
In case you have spent any significant time on the planet of PHP improvement, you recognize that there are purposes that nearly scream: rewrite me!
Maybe you’re right here since you’ve obtained (an issue of) an app identical to that. Or maybe it was simply curiosity? Somehow, I’m going to share my expertise in PHP code refactoring within the type of sensible suggestions primarily based on real-life tasks I took half in.
What’s the issue with refactoring?
Why is it that typically it’s so troublesome for devs to determine a viable manner of refactoring their app?
The first reason behind refactoring issues is fragmentation or lack of correct undertaking information on the appliance’s enterprise mannequin and extra.
When the undertaking information is poor whereas the app nonetheless must be maintained and developed additional, its codebase may be anticipated to get increasingly more out of hand.
In fact, it’s significantly better when the information is fragmented moderately than nonexistent. Within the former case, you’ll be able to collect it and notice all of it down, utilizing each phrases and software program improvement diagrams. Nevertheless, it’s fairly troublesome to be sure that the information fulfills all the necessities of current and future undertaking stakeholders.
When the information is just not there, the scenario will get even worse. Builders want to investigate the app utilizing trial-and-error techniques. It’s messy, and it takes a variety of time.
Fortunately, this excessive scenario is uncommon in observe. Sometimes, we don’t begin fully from scratch. In any case, gathering enterprise information is a course of that takes months and even years.
For optimum outcomes, refactoring efforts needs to be carried out concurrently with producing enterprise information. You’ll be able to analyze every space of a module individually over an prolonged time frame whereas shaping a repeatable refactoring course of for the entire app.
As you’ll be able to see, there are hardly any shortcuts. You’ll want to have a viable refactoring plan.
What refactoring methods in PHP can develop into part of such a course of?
1. Use the one-step-at-a-time strategy
Everybody is aware of this methodology, even when they don’t have anything to do with programming. You employ it while you learn to play the piano, or trip a motorcycle. What does it imply in refactoring?
The gist of it’s to attempt to enhance the code by making small adjustments. It entails bits and items of all the opposite strategies. There isn’t any simple manner of doing this.
In case you spot poorly title variables – right them! In case you discover out that the construction of a given class is inaccurate – change it! Are there lacking varieties someplace? Add them!
The purpose is to not spend an excessive amount of time on it. By making a few small constructive adjustments at a time, you steadily enhance the codebase. In case you get your teammates to do the identical factor, the result’s even higher. Over time, you’ll be able to even refactor the entire app utilizing the method.
2. Take into account the significance of enterprise
Refactoring and enterprise have a troubled relationship.
It’s true {that a} refactored app clearly works higher and has a much more promising future after being made environment friendly and scalable. Alternatively, refactoring typically eats away a variety of programmer’s billable hours and it’s not all the time straightforward to promote its advantages to non-technical folks. In any case, the adjustments made throughout refactoring haven’t any bearing on how the app appears to be like to the person and its exterior habits. To a non-technical individual, they’re largely invisible.
From the attitude of builders themselves, enterprise information can also be essential. As soon as you recognize which modules of the system are most vital from a enterprise perspective, you’ll be able to plan your refactoring course of higher.
Personally, I like to begin with the smallest and least vital modules. That manner, you may get the hold of the system and the fashion of its code by working with the least important components of it. The chance of breaking your entire system and having to revert fully to the previous codebase shrinks.
3. Care for your app construction
Studying all there’s to learn about your system’s code construction is important. No matter how poorly made it’s, that you must research it earlier than you get critical about refactoring.
To point out you simply how vital it’s, let’s analyze an instance app construction impressed by certainly one of my many previous tasks.

The construction above has two primary components:
- a correct app construction primarily based on the Symfony framework,
- parts of a subpar app construction inherited from an out of date a part of the app.
If you wish to refactor a construction like this, that you must concentrate on the out of date half. Usually, it consists of key parts of the app. This specific out of date construction incorporates the CRUD a part of the system that has to do with primary information administration. Sadly, it additionally incorporates vital enterprise logic, together with calculations, and processing guidelines for type information.
In case you work with tasks akin to this one, you’re certain to return throughout a scenario wherein part of the logic is refactored, whereas one other half continues to be offered by the previous system. If you wish to know precisely the place each little bit of performance comes from, that you must be taught the entire construction.
4. Right any bug you notice on the fly
This one must be the shortest piece of recommendation I’ll ever give on this topic.
One of many oldest guidelines of refactoring goes like this: should you change your code in anyplace of your system, be sure to enhance at the very least the fundamental model of it.
Image a operate, methodology, or file that you must change. The code is obvious ugly. It has each tabs and areas, variable names are in a number of languages, naming is non-intuitive, and so forth.
Right at the very least a few of the many issues you’ll be able to discover. That manner, when one other programmer works on that code, they may have fewer issues to cope with. In case your group follows that rule, quickly the standard of the code will enhance considerably.


5. Replace your PHP model
One of many first issues I do as a part of refactoring is replace my PHP model. Not solely will it velocity up the app, however may also make it simpler to identify outdated code. That is extraordinarily vital, as a few of the outdated items of your software program may result in safety points that could be exploited. To place it one other manner, updating your PHP model improves:
- app velocity,
- app stability,
- and the protection of your software program and your total enterprise.
Not dangerous for one thing that takes a few clicks to finish, proper?

Whenever you use an IDE akin to PHPStorm to do the replace, you’re additionally going to get sensible recommendations (together with these in regards to the null coalescing operator) with out the additional third-party instruments.

This easy instance exhibits that ensuring to replace your PHP model has the potential to not solely make your app higher but in addition to alter your very strategy to writing PHP code.
There are some useful instruments that may help you in upgrading your PHP model. Rector is certainly value trying out. It could provide help to transfer from PHP 5.3 all the best way to PHP 8.1.
As soon as PHP is up to date, errors eliminated, out of date features rewritten, and different problematic items of code simplified, you’ll be able to transfer to a different stage of refactoring that has to do with libraries.
6. Replace your libraries

When you find yourself within the early levels of PHP refactoring, inspecting the entire libraries in your undertaking is a should.
In case your system is giant and previous, likelihood is that a few of your libraries usually are not solely outdated however fully deserted by their authors.
Updating is kind of simple. The composer instrument detects outdated/deserted ones. Such libraries typically advocate how greatest to replace or substitute them. The troublesome half is discovering all of the items of code affected by the libraries.
Fortunately, our favourite IDEs come once more to the rescue. Fashionable instruments make it potential to detect all particular cases of the previous library being utilized in your code. In fact, that you must know sufficient in regards to the library to acknowledge its foremost courses, namespaces, constants, or features.
Tackling and bettering these outdated parts will add a variety of vigor and high quality to your code. The efficiency might be improved as effectively.
That’s for the professionals. Sadly, going via the method shouldn’t be all the time such a stroll within the park even with the perfect of IDEs. The issue is that not each outdated library has a correct one-to-one substitute. Items of code affected by the library can’t be refactored. It’s also believable {that a} substitute does exist, however it doesn’t will let you do all the pieces the best way it was finished beforehand.
The latter scenario makes refactoring potential however pricey. A giant a part of the app must be rewritten. Refactoring of this type poses some dangers. The extra obscure the unique library is, the more durable it’s in your IDE and even in your personal set of eyes to seek out all of the items of code affected. On a number of events, I noticed some code being triggered by a set of seemingly random indicators. There isn’t any approach to discover and perceive such code if neither you nor any of your teammates labored on it initially.
7. Do away with outdated options
This one is much less simple than you may suppose at first look. It’s arduous to resolve what’s new sufficient to remain and sufficiently old to do away with objectively.
One easy refactoring trick that may assistance is to concentrate on eradicating outdated database connections, e.g. those who use the MySQL library phased out in PHP 7.0.
One other good observe is to activate the error show by switching the “display_errors = true” choice in php.ini, the. htaccess file, or the ini_set operate. Additionally, you will discover depreciated resolution reviews from error_reporting(E_DEPRECATED) helpful, so flip them on as effectively. Study extra about how PHP may also help you with error reporting.
Even with that assist, this won’t be a simple job. Usually, you’ll be left pissed off, shifting via a mass of code, analyzing it piece by piece. Nonetheless, it’s value doing it should you discover:
- a category,
- a operate,
- or a complete PHP file in want of a substitute for a more recent one.
It’s a lot simpler to right a bug like this now than endure the results of it sooner or later along with your entire teammates.
8. Make sure the separation of applied sciences
The undertaking you inherit is likely to be a bizarre combine of various applied sciences and kinds inside its inside construction. Its readability, extendability, and common developer expertise working with it are going to be poor. The code high quality could also be affected by lifeless code or duplicate code. Eradicating lifeless code and different kinds of redundant code might be a problem for you. Right here is an instance of blended code within the index.php file
You’re certain to return throughout code like this in some older tasks. Whenever you deal with it, the primary and smartest thing you are able to do is attempt to separate one expertise from one other.
Earlier than you get your palms soiled, that you must arrange some guidelines in your code separation efforts. For instance, I typically transfer all of the PHP code into controllers and devoted companies, whereas JavaScript, HTML, and CSS land in fully separate information that use the .js, .html, and .css extensions.
The next instance illustrates the answer for separation of applied sciences:
Whereas the instance illustrates the overall thought effectively, you’ll be able to positively enhance upon it. In an ideal world, your entire HTML part can be moved to a template file akin to twig, whereas all of the PHP code would land within the controller. It may find yourself trying like this:
Though the code right here is kind of easy, the separation clearly improves its readability and extendability. The extra complicated your beginning code is, the extra you’ll enhance it through the use of this system.
The hot button is to arrange an appropriate minimal degree of readability and proceed the refactoring efforts till you attain it. Whenever you try this, you’ll positively get to a degree the place you could have an easy-to-work-with system.
9. Keep your code with static evaluation instruments
Static code evaluation is the mainstay of your refactoring efforts. It holds your code collectively and makes it simpler to get rid of primary errors and misunderstandings (e.g. in case of an indefinite kind taken or returned by a operate).
Within the context of refactoring, an enormous contribution of static evaluation is the best way it will possibly easy out all of the inconsistencies in your code. If it was created by many alternative builders over time, it could embrace completely different coding kinds. When the code construction is respectable, the static evaluation instrument may even discover and proper the entire inconsistencies on the similar time.
Even a single house, lacking or needlessly added, can mess up the code and offer you fairly a headache. Static evaluation could go an extended approach to amend such shortcomings.
And if somebody you recognize must brush up on PHP coding requirements, have them learn the most recent model of PHP Requirements Suggestions (PSR).
Learn extra on static code evaluation in PHP from an article from my colleagues!
- PHP static code evaluation – maintain your code underneath management
10. Check out the Strangler Fig Sample
There are some folks on the market who consider the Strangler Fig Sample as an answer to all refactoring issues.
As it’s possible you’ll already suspect, this isn’t fairly the case. In software program improvement, there are not any one-size-fits-all options. Nonetheless, the Strangler Fig Sample could also be helpful to your refactoring course of.
Strangler Fig Sample – definition
What’s the Strangler Fig Sample? It’s all about constructing a brand new system across the previous one (strangling the previous one with the brand new one) till the latter shouldn’t be wanted anymore.

Strangler Fig Sample – advantages
This strategy has some main advantages.
The brand new system in improvement shouldn’t collide with the prevailing one. As the brand new one matures, its particular person modules can steadily substitute the previous system.
Because the duties are being transferred to the brand new system, it’s straightforward to watch and examine their efficiency. You’ll be able to steadily get rid of all the issues ought to they come up.
Generally, monitoring is extra of a necessity than an non-obligatory task. It permits your group to be taught extra about bits and items of the previous system that you just don’t learn about both as a result of incomplete enterprise information or the bizarre nature of the legacy code.
use the Strangler Fig Sample?
You have to be superb so long as you keep on with a few primary steps:
-
Outline the interface of what you wish to transfer
It’s a necessary step as a result of the interface consists of instructions on how the brand new code and modules are alleged to work.
-
Delegate duties from the previous system to the brand new one
If there’s a piece of code in your new system that may substitute a bit of code from the previous system, make the swap as quickly as potential.
-
Outline a brand new single supply of fact
A well-designed system has a single supply of fact (SSOT). It ought to have all information required by your system’s modules. As you progress to the brand new system, be sure to not compromise your SSOT.
-
Add all the brand new functionalities within the new system solely
It ought to go with out saying, however sadly, it doesn’t all the time occur. In case you proceed to increase your previous codebase, you delay the second when the brand new system takes over fully and threat having to jot down the identical performance twice.
-
Flip off the previous code altogether when the time comes
As soon as all of the functionalities are moved to the brand new system, flip off or take away the previous code.
The Strangler Fig Patten is a fashionable resolution to the issue of outdated code. It’s value remembering that you just don’t all the time have to maneuver your entire codebase. Typically, it’s possible you’ll select to make use of the sample for particular modules or functionalities.
There isn’t any hard-and-fast rule for utilizing the sample. The very best plan of action must be determined individually for every undertaking.
11. Additional tip – testing new code
As cliche because it sounds, testing is a steady course of. Every new testable performance in your system ought to have:
- unit checks,
- practical checks,
- integration checks.
Along with that, you need to nonetheless check manually. That allows you to discover bugs that is likely to be missed by the instruments you employ.
The important thing phrase right here is “testable” – not each piece of code meets this requirement. Don’t fall into the lure of testing actually all the pieces. It’ll take extra time and it’s value it.
12. Naming
If you wish to be thorough along with your refactoring efforts, you need to attempt to enhance the names of variables, strategies, or features wherever you’ll be able to. Their names needs to be indicative of what they do.
Let’s take the next code that checks for the person kind:
You’ll be able to modify it in three other ways:
The primary one is a standard strategy wherein the title signifies the person kind. As well as, the title of a way modified from kind to isType to higher mirror what’s checked. The kind methodology itself shouldn’t verify for the person kind, however merely return details about it.
The second is rather more fascinating. This time, you’re asking particularly if the person is a moderator. The entire operation now takes place within the mannequin itself or the person object.
The third model builds upon the primary one. The distinction is that you just don’t use character strings brazenly, however solely by way of static values assigned to the mannequin or person object. Observe that this model is also utilized to model two – the static values can be checked for within the mannequin or person object.
To take the refactoring even additional, you’ll be able to summary constants such because the aforementioned moderator to an enum. It ought to make the habits of person varieties extra orderly and predictable sooner or later.
Remember that in keeping with the Single Accountability rule, the person kind shouldn’t be depending on the person object. A unique object needs to be chargeable for it as an alternative.
Bonus – refactoring with Synthetic Intelligence!
Stunned? These days, they use AI-powered expertise for nearly all the pieces so why not code refactoring?
I’m not going to attempt to provide you with any particular applied sciences beforehand. I’m merely going to ask ChatGPT model 4 what it will possibly do for me. As for code, I’m going to make use of the file generator I created within the Extracting part above. I selected the model that does NOT embrace the csv operate (fputcsv).
Immediate:
Hey, may you apply some refactoring strategies to this code?
Immediate:
Hey, may you apply some refactoring strategies to this code?
{HERE WAS THE CODE}
If what they are saying is true, along with refactoring the code, ChatGPT will share some recommendation on implement these optimizations.
The recommendation is right here certainly. It’s fairly common however nonetheless useful. I’m pasting it right here as is:
This PHP code may be refactored for higher readability and maintainability, and to stick to single duty ideas. Right here’s the way you may refactor it:
- Single Accountability Precept: Separate the issues by creating courses that deal with one particular factor. As an example, you might have one class for producing JSON, one other for CSV, and one other one for dealing with the output to the browser.
- Code Duplication: The headers and output buffering code are duplicated in each strategies. This may be extracted into its methodology.
- String Literals: The code has just a few syntax points with the string literals, utilizing curly quotes as an alternative of straight quotes. This must be corrected.
- Magic Strings: The content material kind strings and file names are “magic strings” and may very well be extracted to class constants for simpler administration and adjustments.
- Complexity in generateCsvFile: The CSV era logic is complicated and may very well be simplified or damaged down into smaller strategies.
- Error Dealing with: There’s no error dealing with for the JSON_encode or file operations.
Right here’s a refactored model of the code:
There’s additionally a high-level recap of what ChatGPT precisely did to the code:
- Created two separate courses JsonResponseGenerator and CsvResponseGenerator following the Single Accountability Precept.
- Created a non-public outputContent methodology to take away duplication.
- Mounted string literals to make use of correct quotes.
- Added primary error dealing with for JSON encoding.
- Extracted magic strings to class constants.
- Broke down the CSV content material era into smaller strategies for readability.
Did ChatGPT do an excellent job? Total, I’d say that it did. It doesn’t imply that the refactoring couldn’t have been higher. For instance:
- it didn’t take the chance to make use of two courses in a single generator to generate a file in keeping with its kind.
- It failed to make use of a standard interface for these two courses.
On the intense facet, I’m impressed that the AI included error dealing with. I didn’t try this in my examples on objective and I’m very impressed that this AI does it by default.
Naturally, a check so simple as this one can’t mirror the complexity of enterprise logic and the technological range of a industrial undertaking.
Regardless of all of its energy, AI nonetheless can’t perceive the enterprise context of an app. For higher or worse, that is nonetheless one thing solely us builders can do.
Refactoring PHP code – 3 key takeaways
As you’ll be able to, there’s a lot to contemplate when refactoring your present code:
- The enterprise actuality of your software program could decide simply how a lot you’ll be able to refactor and the place to start.
- The standard, construction, and age of your code will resolve the strategy and the way a lot work you actually have readily available. And as you recognize very effectively, these components could range rather a lot in the case of the PHP programming language.
- The scale of your group and the extent to which you prioritize scalability, in addition to the steady availability of your software program, will make an enormous distinction.
Even placing that apart, refactoring continues to be unpredictable. When you begin working with a big piece of legacy code, you may discover out that your adjustments trigger different surprising adjustments. It could take a variety of time and PHP examples to determine all the pieces. Simply how a lot? Not even your undertaking supervisor dares to guess!
That’s why my ultimate piece of recommendation is – to spend as a lot as you’ll be able to afford on the preliminary evaluation.
Design a customized refactoring course of in your undertaking that will get the many of the restricted time and assets you could have. That is the best way to attain sustainable code!
Are you searching for expert PHP builders to refactor your system?
The Software program Home gives entry to many expert PHP devs that participated in giant commercially profitable tasks identical to these described within the article.