Home » Php » php – How to automate property generation for a class in phpstorm?

php – How to automate property generation for a class in phpstorm?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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;
    }
}

Answer:

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