PhpStorm 2020.2 Help

Extract class

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.

  1. Position 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.

  2. From the main menu, select Refactor | Extract | Extract Class or press Ctrl+Alt+Shift+T and in the popup menu, select Extract Class.

  3. 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.

    PhpStorm. Extract class refactoring
  4. 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 Target and moves the bar method's implementation into this class.

  • An instance of the Target class is injected into Source via the constructor.

  • To provide access to the private property foo, the get_foo getter method is generated within the Source class. This is achieved by enabling the Generate accessors option in the Extract To Class dialog.

  • The (new Source())->bar() method call doesn't change, but the actual execution is now delegated to the bar method of the Target class.

class Source { private $foo; public function bar() { echo $this->foo; } } (new Source())->bar();
class Source { private $foo; /** @var \Target */ private $target; public function __construct() { $this->target = new \Target($this); } public function bar() { $this->target->bar(); } public function get_foo() { return $this->foo; } } class Target { private $source; public function __construct(Source $source) { $this->source = $source; } public function bar() { echo $this->source->get_foo(); } } (new Source())->bar();
Last modified: 20 July 2020