PhpStorm lets you use refactorings that extract class methods and properties into a new class. These refactorings are useful when a class has grown too large and "does too many things". In such cases, it may be a good idea to split the class into smaller, more cohesive classes. Additionally, you can extract functions defined in php files into new classes. This may be useful for grouping related functionality into utility classes, avoiding collisions for non-namespaced methods, or representing your codebase in an object-oriented manner.
Place the caret at a code fragment that you want to extract into a class. You can extract PHP class properties and methods as well as standalone functions.
Go to Extract Class.or press Control+Alt+Shift+T and in the popup menu, select
In the dialog that opens, specify the target namespace and destination directory, the desired name of a new class, and the class members or standalone functions to extract. To generate accessor and mutator methods (getters and setters) for the fields of your classes, select the Generate accessors checkbox.
Preview your changes and click OK.
Extract Class example
In the following example, the
bar method is extracted from the
Source class to a new
Target class. During the refactoring, the following happens:
PhpStorm creates a new class
Targetand moves the
barmethod's implementation into this class.
An instance of the
Targetclass is injected into
Sourcevia the constructor.
To provide access to the private property
get_foogetter method is generated within the
Sourceclass. This is achieved by enabling the Generate accessors option in the Extract To Class dialog.
(new Source())->bar()method call doesn't change, but the actual execution is now delegated to the
barmethod of the