Working with UML class diagrams in PhpStorm
It can be really handy to have a schematical view of an application’s class hierarchy. PhpStorm lets us quickly examine our application structure by generating UML class diagrams. This can help us understand the codebase we’re working on and navigate from diagram to code and back. We can even refactor from the UML diagram! Let’s see how.
View UML class diagram
From the project structure or with our cursor on a class name in the editor window, we can use the Diagram | Show Diagram context menu to generate a UML diagram. Alternatively, Ctrl+Shift+Alt+U (Cmd+Shift+Alt+U on Mac) will open a new editor tab and display a UML diagram for the class. Note that the context menu also has a Show Diagram in pop-up item which displays an overlay containing the requested UML diagram.
From the diagram’s toolbar we can select to show or hide fields, constructors and methods. We can drag other files from our project onto the diagram and have them visually represented. Drawing additional relationships and adding notes is also supported, to help us understand the code base we’re working on.
We can move around classes and have PhpStorm layout the diagram. Right-click the diagram surface and explore the context menus! If a parent class is not on the diagram, Ctrl+Alt+P (Cmd+Alt+P on Mac) will add it. Ctrl+Alt+B (Cmd+Alt+B on Mac) will add implementations of a class to the diagram as well.
Navigate between diagram and code
From a UML diagram, we don’t always know what a class, field or method is doing. By clicking the element in the diagram and using the F4 shortcut (Jump to Source), we can navigate to the source code for the element.
Find usages is supported as well: select a class or class member and use the Find Usages (Alt+F7) context menu.
Refactoring from the UML diagram
Many refactorings can easily be done from the UML class diagram. Need to rename a class or a member of that class? Select it and use the Refactor | Rename… context menu (Shift+F6).
We can also change a method’s signature from our UML diagram and do things like reordering parameters and changing visibility.
Viewing changes as diagram
An interesting feature of UML class diagrams in PhpStorm is that when our code is under source control, it allows us to evaluate how our code changes affect the application model. Whenever changes have been made, use the Diagrams | Show Changes context menu (or Ctrl+Alt+Shift+D / Cmd+Alt+Shift+D on Mac). This will open up a visual representation of code that has been modified.
In the above example we see that in the UsersController a new function named post() has been added (green). The get() method has been changed (blue). We’ve also added a variable to the ApiControllerBase.
As always, we appreciate your feedback in the comments below or in our forums!
Develop with pleasure!
– JetBrains PhpStorm Team