PHP code refactoring – sensible suggestions with code examples

From determining the system construction, by means of static code evaluation, to updating your libraries, and far more – there are lots of methods to go about PHP code refactoring. Nonetheless, an important step is to create a viable refactoring course of to your particular software. Learn this intensive tutorial and get the perfect insights from a developer who refactors for a dwelling.
In the middle of my profession as a PHP developer, I noticed and labored on lots of PHP apps in want of refactoring. They’d all kinds of issues, however all of them stemmed from a short-sighted method to improvement. The very first thing to do to refactor them is to alter this method.
However what to do subsequent? In any case, every app is totally different. Whereas there isn’t a one-size-fits-all resolution, I’m going to give you the following smartest thing within the type of sensible PHP refactoring suggestions based mostly on my on a regular basis expertise.
You probably have spent any significant time on the earth of PHP improvement, you already know that there are functions that nearly scream: rewrite me!
Maybe you’re right here since you’ve received (an issue of) an app similar to that. Or maybe it was simply curiosity? Someway, I’m going to share my expertise in PHP code refactoring as 10 sensible suggestions based mostly on real-life tasks I took half in.
What’s the issue with refactoring?
Why is it that typically it’s so tough for devs to determine a viable manner of refactoring their app?
The first explanation for refactoring issues is fragmentation or lack of correct mission information on the applying’s enterprise mannequin and extra.
When the mission 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 may collect it and notice all of it down, utilizing each phrases and software program improvement diagrams. Nonetheless, it’s fairly tough to ensure that the information fulfills all the necessities of current and future mission stakeholders.
When the information is solely not there, the scenario will get even worse. Builders want to research the app utilizing trial-and-error techniques. It’s messy, and it takes lots of time.
Fortunately, this excessive scenario is uncommon in apply. Usually, we don’t begin utterly from scratch. In any case, gathering enterprise information is a course of that takes months and even years.
For optimum outcomes, refactoring efforts ought to be carried out concurrently with producing enterprise information. You possibly can analyze each space of a module individually over an prolonged time frame whereas shaping a repeatable refactoring course of for the entire app.
As you may see, there are hardly any shortcuts. You want to have a viable refactoring plan.
What refactoring strategies in PHP can turn out to be part of such a course of?
1. Use the one-step-at-a-time method
Everybody is aware of this methodology, even when they don’t have anything to do with programming. You employ it if you learn to play the piano, or journey a motorbike. 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 is no such thing as a simple manner of doing this.
For those who spot poorly title variables – appropriate them! For those who discover out that the construction of a given class is inaccurate – change it! Are there lacking sorts 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. For those who get your teammates to do the identical factor, the result’s even higher. Over time, you may even refactor the entire app utilizing the method.
2. Think about 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. Then again, refactoring usually eats away lots 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 don’t have any bearing on how the app appears to be like to the person and its exterior conduct. 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 already know which modules of the system are most essential from a enterprise perspective, you may plan your refactoring course of higher.
Personally, I like to begin with the smallest and least essential modules. That manner, you may get the cling of the system and the model of its code by working with the least important elements of it. The chance of breaking all the system and having to revert totally to the previous codebase shrinks.
3. Care for your app construction
Studying all there’s to find out about your system’s code construction is crucial. No matter how poorly made it’s, it is advisable to examine it earlier than you get critical about refactoring.
To point out you simply how essential it’s, let’s analyze an instance app construction impressed by one in every of my many previous tasks.

The construction above has two primary elements:
- a correct app construction based mostly on the Symfony framework,
- components 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, it is advisable to give attention to the out of date half. Usually, it consists of key components of the app. This specific out of date construction accommodates the CRUD a part of the system that has to do with primary knowledge administration. Sadly, it additionally accommodates essential enterprise logic, together with calculations, and processing guidelines for type knowledge.
For those who work with tasks equivalent to this one, you’re certain to return throughout a scenario wherein part of the logic is refactored, whereas one other half remains to be supplied by the previous system. If you wish to know precisely the place each little bit of performance comes from, it is advisable to study the entire construction.
4. Appropriate 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: if you happen to change your code in anyplace of your system, be certain to enhance not less than the fundamental model of it.
Image a operate, methodology, or file it is advisable to 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.
Appropriate not less than a number 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 take care of. In case your workforce 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 pace up the app, however may also make it simpler to identify outdated code. That is extraordinarily essential, as a number of the outdated items of your software program may result in safety points which may be exploited. To place it one other manner, updating your PHP model improves:
- app pace,
- app stability,
- and the protection of your software program and your whole enterprise.
Not unhealthy for one thing that takes a few clicks to finish, proper?

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

This easy instance reveals that ensuring to replace your PHP model has the potential to not solely make your app higher but in addition to alter your very method to writing PHP code.
There are some helpful instruments that may help you in upgrading your PHP model. Rector is unquestionably price trying out. It could aid you 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 capabilities rewritten, and different problematic items of code simplified, you may transfer to a different stage of refactoring that has to do with libraries.
6. Replace your libraries

If you end up within the early phases of PHP refactoring, inspecting all the libraries in your mission is a should.
In case your system is massive and previous, likelihood is that a few of your libraries usually are not solely outdated however totally deserted by their authors.
Updating is kind of simple. The composer device detects outdated/deserted ones. Such libraries usually advocate how greatest to replace or exchange them. The tough half is discovering all of the items of code affected by the libraries.
Fortunately, our favourite IDEs come once more to the rescue. Trendy instruments make it doable to detect all particular situations of the previous library being utilized in your code. In fact, it is advisable to know sufficient concerning the library to acknowledge its foremost courses, namespaces, constants, or capabilities.
Tackling and bettering these outdated components will add lots of vigor and high quality to your code. The efficiency will likely be improved as properly.
That’s for the professionals. Sadly, going by means of the method isn’t 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 alternative. Items of code affected by the library can’t be refactored. It is usually believable {that a} alternative does exist, however it doesn’t let you do every thing the best way it was completed beforehand.
The latter scenario makes refactoring doable however expensive. An enormous a part of the app must be rewritten. Refactoring of this type poses some dangers. The extra obscure the unique library is, the tougher it’s to your IDE and even to your personal set of eyes to search 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 is no such thing as a strategy 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 onerous to resolve what’s new sufficient to remain and sufficiently old to eliminate objectively.
One easy refactoring trick that may assistance is to give attention to eradicating outdated database connections, e.g. people who use the MySQL library phased out in PHP 7.0.
One other good apply is to activate the error show by switching the “display_errors = true” possibility in php.ini, the. htaccess file, or the ini_set operate. Additionally, you will discover depreciated resolution studies from error_reporting(E_DEPRECATED) helpful, so flip them on as properly. Study extra about how PHP may help you with error reporting.
Even with that assist, this won’t be a simple job. Usually, you’ll be left pissed off, shifting by means of a mass of code, analyzing it piece by piece. Nonetheless, it’s price doing it if you happen to discover:
- a category,
- a operate,
- or an entire PHP file in want of a alternative for a more moderen one.
It’s a lot simpler to appropriate a bug like this now than undergo the implications of it sooner or later along with your whole teammates.
8. Make sure the separation of applied sciences
The mission you inherit is perhaps a bizarre combine of various applied sciences and kinds. Its readability, extendability, and common developer expertise working with it are going to be poor. 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 sort out 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 arms soiled, it is advisable to arrange some guidelines to your code separation efforts. For instance, I usually transfer all of the PHP code into controllers and devoted providers, whereas JavaScript, HTML, and CSS land in totally separate recordsdata that use the .js, .html, and .css extensions.
The next instance illustrates the answer for separation of applied sciences:
Whereas the instance illustrates the final concept properly, you may positively enhance upon it. In an ideal world, all the HTML part can be moved to a template file equivalent to twig, whereas all of the PHP code would land within the controller. It may find yourself wanting like this:
Though the code right here is kind of easy, the separation clearly improves its readability and extendability. The extra advanced your beginning code is, the extra you’ll enhance it by utilizing this method.
The secret is to arrange a suitable minimal degree of readability and proceed the refactoring efforts till you attain it. Whenever you do this, you’ll positively get to some extent the place you’ve 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 remove primary errors and misunderstandings (e.g. in case of an indefinite kind taken or returned by a operate).
Within the context of refactoring, a giant contribution of static evaluation is the best way it may well clean out all of the inconsistencies in your code. If it was created by many alternative builders over time, it might embody totally different coding kinds. When the code construction is respectable, the static evaluation device may even discover and proper all the inconsistencies on the identical time.
Even a single house, lacking or needlessly added, can mess up the code and offer you fairly a headache. Static evaluation could go a protracted strategy to amend such shortcomings.
And if somebody you already know 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!
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 you could 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 isn’t wanted anymore.

Strangler Fig Sample – advantages
This method has some main advantages.
The brand new system in improvement shouldn’t collide with the present one. As the brand new one matures, its particular person modules can steadily exchange the previous system.
Because the duties are being transferred to the brand new system, it’s straightforward to observe and evaluate their efficiency. You possibly can steadily remove all the issues ought to they come up.
Generally, monitoring is extra of a necessity than an non-obligatory project. It permits your workforce to study extra about bits and items of the previous system that you simply don’t find out about both as a consequence of incomplete enterprise information or the weird nature of the legacy code.
The best way to use the Strangler Fig Sample?
You have to be advantageous so long as you stick with a few primary steps:
-
Outline the interface of what you need to transfer
It’s an important step as a result of the interface consists of instructions on how the brand new code and modules are speculated 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 exchange a bit of code from the previous system, make the swap as quickly as doable.
-
Outline a brand new single supply of reality
A well-designed system has a single supply of reality (SSOT). It ought to have all knowledge required by your system’s modules. As you progress to the brand new system, be certain 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. For those who proceed to develop your previous codebase, you delay the second when the brand new system takes over utterly and threat having to write 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 price remembering that you simply don’t all the time have to maneuver all the codebase. Typically, you could select to make use of the sample for particular modules or functionalities.
There is no such thing as a hard-and-fast rule for utilizing the sample. The most effective plan of action must be determined individually for each mission.
Refactoring PHP code – 3 key takeaways
As you may, there’s a lot to think about when refactoring your present code:
- The enterprise actuality of your software program could decide simply how a lot you may refactor and the place to start.
- The standard, construction, and age of your code will resolve the method and the way a lot work you actually have available. And as you already know very properly, these elements could fluctuate lots on the subject of the PHP programming language.
- The dimensions of your workforce and the extent to which you prioritize scalability, in addition to the steady availability of your software program, will make a giant distinction.
Even placing that apart, refactoring remains 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 lots of time and PHP examples to determine every thing. Simply how a lot? Not even your mission supervisor dares to guess!
That’s why my closing piece of recommendation is – to spend as a lot as you may afford on the preliminary evaluation.
Design a customized refactoring course of to your mission that will get the many of the restricted time and sources you’ve. That is the best way to realize sustainable code!
Are you in search of expert PHP builders to refactor your system?
The Software program Home supplies entry to many expert PHP devs that participated in massive commercially profitable tasks similar to these described within the article.