PhpStorm and code completion for $this⁠-⁠>⁠template

2 years ago by David Grudl  

How to get rid of PhpStorm alerts on “undefined fields” and activate the code completion for $this->template in presenters?

So how to change this view with the underlined abc and the empty pop-up window:

Into this?

Simply. Just add the following annotation to the presenter (for example to BasePresenter):

 * @property-read \Nette\Bridges\ApplicationLatte\Template|\stdClass $template
abstract class BasePresenter extends Nette\Application\UI\Presenter

Note: In the latest versions of Nette, this annotation will be directly in the code.

Template class

The stdClass class in the annotation is a workaround for PhpStorm, which otherwise treats all variables as undefined. However, it is more interesting to create a class with a real list of the variables that the template uses, including their types. It may look like this:

 * @property string $lang
 * @property int $page
 * @property string[] $menu
 * @property Model\Page $article
class ArticleTemplate

And then put it in the annotation of a specific presenter instead of stdClass:

 * @property-read ArticleTemplate|\Nette\Bridges\ApplicationLatte\Template $template
final class ArticlePresenter extends Nette\Application\UI\Presenter

From now on, the message is perfect:

We still have to solve the suggestion in the template. So far, Latte plugin can't do it, but once it can, it could use the same template class. For example, there could be a new macro {templateType App\Presenters\ArticleTemplate} that will pass the template class name.