Code Refactoring In PhpStorm

Code refactoring in PhpStorm

PHP refactoring is really cool! But in the process of fulfilling it, some routine operations and repetitive actions with the code are rather frequent. And in the end there still may remain a lot of syntax errors. Well it often kills any initiative. And surely this is not cool. Fortunately, modern IDE are able to take part of the tasks for themselves while the developer can concentrate on the process of refactoring of code and architecture as a whole, rather than on the fight against boring code.

phpstorm Some time ago I have even replaced free NetBeans with paid PhpStorm that has better implementation of refactoring. And believe me, it was worth it!

I’d like to start with a small remark about refactoring of code. To execute any command in the storm, call any function, and spy any shortcut — it’s enough to remember only one key combination: Shift+Ctr/⌘+A (or Help → Find Action..., even if this one is forgotten).

For example, a list of ToDo:

PhpStorm: Refactoring

So, let’s start our refactoring. We could always come across some sections of code where the methods would grow to such an extent that even-booze-shots-would-not-help. So, they «get it hot» first. Still what a hard job it is to allocate manually comparatively integral separate part, form it in a separate method, arrange all the necessary variables and write them into arguments, add the ​​returned values in the newly invented method. And how many those bugs will appear in the process? No, down with this damned refactoring. Works — don’t touch! And now let’s try this, but using IDE.

Extract Method Refactoring / Function

Here you are, for example, a wonderful piece of code that just asks for decomposition.

php refactoring

Select our sheet code and… vaguely start remembering ... where could be this Extract Method, and what are its hotkeys: \
And while the use does not come to automatism – let’s remember about the universal code Find Action, which is perfect for finding the action even by the part of its names.

PhpStorm: Refactoring

Okay, we start up our action — ops...

PhpStorm: Refactoring

Hah, I accidentally allocated break; at the end of the block, IDE noticed it smartly, and prevented me from a sad mistake. Such automatic checks are very useful in case of refactoring any large piece of code, for example, like in a loop:

PhpStorm: Refactoring

After we identified the safe piece of code and run Extract Method, a dialog box appears.

In that box we need to somehow call our method, to specify its visibility and sort out the order of the arguments, if necessary.

PhpStorm: Refactoring

By the way, personally I use this dialog to determine the dependency of the «external» variables for an arbitrary piece of code that is very helpful in complex refactoring.

A few more examples: ‘Extract Function/Method’ refactoring for PHP

Introduce Variable

The blog IDE gives such an example, but I use this functional a little differently. For example, we have such section of code:

PhpStorm: Refactoring

Here the meaning is not clear right away, and formatting this code is an inconvenient procedure.
Select the first logical part,

PhpStorm: Refactoring

and run Introduce Variable (Refactor → Extract → Variable...), enter the name of the variable in the appeared dialog.

PhpStorm: Refactoring

We proceed similarly with the rest of the code. As a result the code is much clearer; and it’s easier to understand the logic in these conditions.

PhpStorm: Refactoring

Inline Variable

And if you’re too lazy to manually allocate piece of code to export to a variable — the storm can do it as well. Put the cursor somewhere nearby, run Refactor → Extract → Variable...), but this time instead of the dialog box, a drop-down list appears from which we can choose the appropriate block of code. And IDE has kindly allocated it for us.

PhpStorm: Refactoring

Introduce Field

This function works similarly, it only adds a property of the class instead of variable. Refactor → Extract → Field...

PhpStorm: Refactoring

You can set the visibility of properties, as well as a place where to declare it (in the current method, description of class or in the constructor).

Introduce Constant

The same principle can be used to allocate frequently repetitive lines in constants. Refactor → Extract → Constant...

PhpStorm: Refactoring

The name of the constant was suggested by IDE itself. All we need is just hit Enter to admire the result.

PhpStorm: Refactoring

Rename Refactoring

Renaming mechanism, is anyone here could do without it? It is clearly described in the IDE blog, so I will not be repetitive: New Rename refactoring features in PhpStorm 2.0

Getter/Setter

Essences in Doctrine 2 (while using annotations for their announcement) give an illustrative example where the automatic generation of accessors / mutators is greatly helpful. Simply describe the properties of the class, then call Code → Generate → Getters and Setters, and choose for which properties we should generate methods.

PhpStorm: Refactoring

And here is the result of our «quick and easy» works.

PhpStorm: Refactoring

If the format is not very suitable, generation templates can be corrected in your own way.

Editing templates of generation methods get * / set *.

Surround With

«Wrapping» code in typical if(expr){…} and while(expr){…}. It’s described in detail in the IDE blog: New in 3.0: More ‘Surround With’ actions for PHP

Smart Duplicated Code Detector

This is the wonderful thing that helps to find duplicate directly from the IDE, instead of running console utilities with their «hollow» and uninformative reports.

It starts out from here: Code → Locate Duplicates...

extract method refactoring

Found duplicates are sorted by relevance (cost). The higher they are — the sadder is the situation in the code. It’s convenient that the code in the preview window, can be scaled and edited. That simplifies the process of refactoring.

PHP Code Sniffer

Just don’t forget to adjust Code Sniffer, moreover, its support is now integrated in the IDE.

Using: Checking your code with PHP Code Sniffer in PhpStorm 4.0
Advanced Setup: Advanced PHP Code Sniffer Options in PhpStorm 5.0

Mini Tips

1. Closed the file / lost the place where the last changes were made? It does not matter! Navigate → Last Edit Location

2. Use the rectangular selection code refactoring tool (middle mouse button or enable / disable Column Selection Mode in the context menu)

PhpStorm: Refactoring

If you start writing with so selected code block — all the lines will change simultaneously.

PhpStorm: Refactoring

3. Use the Live Templates

4. Effectively manage different To-do’s

5. Local History rules!

6. And not to forget about the most convenient history of clipboard that is called with a standard hotkey of the insert +Shift (or Edit → Paste from History...)

refactoring of code

And Some Entertaining Statistics

PhpStorm collects statistics by which it determines the most commonly used features at work, and suggests what still should be used more often.

P.S. Oh, and look at the paragraph on top, well, isn’t PhpStorm a dear? ;)

code refactoring tool

Related Material

This article is just a starting point of a series of notes about PhpStorm. Next in line is how to deal with code debugging by means of this wonderful IDE and xdebug. Applications for the rest of the hot topics are received in the comments. And more info on our Symfony Experience and expertize is here.