Constructor Property Promotion

YouTube player

With the advent of Magento 2.4.4 and subsequent versions embracing PHP 8, we’re poised to leverage the innovative constructor property promotion feature introduced in PHP 8. This powerful feature streamlines our coding efforts significantly.

Traditionally, the practice involved declaring a class property separately and then initializing it within the constructor. Constructor property promotion elegantly condenses this two-step process.

<?php

declare(strict_types=1);

namespace Itcforu\Kickstart\Model;

class Product {

    /**
     * @param Category $category
     */
    public function __construct(private Category $category,){}

    /**
     * @return string
     */
    function getCategoryName(): string
    {
        return $this->category->getName();
    }
}

By simply specifying the property’s visibility within the constructor’s parameters, we achieve the same outcome more succinctly:

This refined approach retains the original functionality while minimizing the code footprint.

For enhanced readability, especially when dealing with numerous dependencies, it’s advisable to format constructor arguments with line breaks. PHP 8 further enhances this by allowing a trailing comma in the argument list, reducing the potential for version control conflicts.

Embracing constructor property promotion in new Magento development projects is something I advocate strongly for. The efficiency and clarity it brings to the code are invaluable.