如何自动为phpstorm中的类生成属性? [英] 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?
推荐答案
您可以使用Initialize field
功能.
这样,您只需要这样编写构造方法:
This way, you only have to write the constructor method this way:
class SomeNewService {
public function __construct(TwigEngine $engine, KernelInterface $kernel, LoggerInterface $logger) {
}
}
然后,您可以使用初始化字段.将光标移到构造函数的一个属性上,然后在MacOS上使用 Alt + Enter .
Then you can use initialize fields. Get the cursor over one property of the constructor, then on MacOS use Alt + Enter.
它看起来像这样:
按Enter键后,您将看到一个属性列表,可以通过 Shift 和箭头键进行选择.通过选择所有属性,您的代码将如下所示:
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;
}
}
这篇关于如何自动为phpstorm中的类生成属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!