magento / magento/magento-coding-standard

[New Rule] Do not use setTemplate in Block classes

Open
#31 5 comments 2 reactions 0 assignees View on GitHub
need to discuss new rule proposal
Dominant language
PHP
Stars
375
Forks
165
PR merge metrics
No merged PRs in 30d

Description

### Background
When creating a Block class, a Block class could set its PHTML template in multiple ways: Through XML layout, through a call to `$this->setTemplate()` and through a variable $_template. The new design of Block classes is to configure them at constructor time, meaning that configuration options (like the template) are added using constructor arguments. This allows for the XML layout to change the template. The template in the Block class is then only defined as a default value, if the XML layout is not overriding the template: This default value is best defined via a protected variable `$_template`.
### Reason
If `$this->setTemplate()` is used instead, this could lead to potential issues: First of all, setters are deprecated in Block classes (because constructor arguments should be preferred instead). Second, if `$this->setTemplate()` is added to the constructor after calling upon the parent constructor, it would undo the configuration via XML layout. Simply put: It is outdated and leads to issues quickly.
### Implementation
[ExtDn SetTemplateInBlockSniff](https://github.com/extdn/extdn-phpcs/blob/master/Extdn/Sniffs/Blocks/SetTemplateInBlockSniff.php).

Contributor guide

Open the contributing guide

Research direction

Start with ExtDn/Sniffs/Blocks/SetTemplateInBlockSniff.php, the implementation referenced by the issue, and inspect how the coding standard identifies Block classes and setTemplate calls. Done means the new rule is applied to the intended Block classes and catches the prohibited usage without flagging allowed cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.