k0pernikus
k0pernikus

Reputation: 66817

How to automate property generation for a class in phpstorm?

If I implement a class, which gets some services injected, I have to write this bulk of code:

<?php
namespace Hn\AssetDbBundle\Services;

use Psr\Log\LoggerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * Class SomeNewService
 * @package Hn\AssetDbBundle\Services
 */

class SomeNewService {
    /**
     * @var TwigEngine
     */
    private $engine;
    /**
     * @var KernelInterface
     */
    private $kernel;
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(TwigEngine $engine, KernelInterface $kernel, LoggerInterface $logger) {
        $this->engine = $engine;
        $this->kernel = $kernel;
        $this->logger = $logger;
    }
}

This seems redundant. Is there a way I can reduce the amount of code I have to write? Is there a live template for initializing the fields or can I autogenerate the bulk of this block otherwise?

Upvotes: 11

Views: 7955

Answers (3)

Hesam Moosapour
Hesam Moosapour

Reputation: 592

On Windows : put the cursor on the arguemnt of your construct method , then press Alt + Enter , hover/selct over initialize field , then press Alt + Enter , then select field & press Ok .

Enjoy

Upvotes: 0

whitezo
whitezo

Reputation: 325

You can also do the other way around, defining the properties first, and then in the "Generate" menu (Cmd+N), use "Constructor".

Upvotes: 4

k0pernikus
k0pernikus

Reputation: 66817

You can use the Initialize field feature.

This way, you only have to write the constructor method this way:

class SomeNewService {
    public function __construct(TwigEngine $engine, KernelInterface $kernel, LoggerInterface $logger) {        
    }
}

Then you can use initialize fields. Get the cursor over one property of the constructor, then on MacOS use Alt + Enter.

It looks something like this:

Initalize fields feature

After you press enter you are confronted with a list of properties, which you can select by Shift and arrow keys. By selection all the properties, your code will look like this:

    class SomeNewService {
    /**
     * @var TwigEngine
     */
    private $engine;
    /**
     * @var KernelInterface
     */
    private $kernel;
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param TwigEngine $engine
     * @param KernelInterface $kernel
     * @param LoggerInterface $logger
     */
    public function __construct(TwigEngine $engine, KernelInterface $kernel, LoggerInterface $logger) {
        $this->engine = $engine;
        $this->kernel = $kernel;
        $this->logger = $logger;
    }
}

Upvotes: 27

Related Questions