Mohamed Abbas | Architect Magento | Tech Blogger | Magento Trainer

Mohamed Abbas
Mohamed Abbas
Architect Magento | Tech Blogger | Magento Trainer

PHP 8 Constructor Property Promotion in Magento 2 Development

With the release of PHP 8, Magento 2 developers can leverage the powerful Constructor Property Promotion feature to simplify their code. Since Magento 2.4.4 and later officially supports PHP 8.1, this is a great opportunity to clean up constructor-heavy classes commonly used in Magento modules.

In this blog, we’ll explore how Constructor Property Promotion can be used in Magento 2 development to make your code cleaner and more maintainable.

Why Constructor Property Promotion Matters in Magento 2

Magento 2 relies heavily on Dependency Injection (DI) for managing class dependencies. This often results in constructors with multiple dependencies and explicit property declarations, leading to verbose and repetitive code.

Before PHP 8, a Magento 2 class constructor might look like this:

				
					<?php
namespace Abbasm\HelloWorld\Model;

class CustomModel
{
    private \Magento\Catalog\Model\ProductRepository $productRepository;
    private \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig;
    private \Psr\Log\LoggerInterface $logger;

    public function __construct(
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->productRepository = $productRepository;
        $this->scopeConfig = $scopeConfig;
        $this->logger = $logger;
    }
}

				
			

While this structure works, it involves a lot of boilerplate code. Constructor Property Promotion eliminates this redundancy.

Using Constructor Property Promotion in Magento 2

With PHP 8, the above class can be simplified as follows:

				
					<?php
namespace Abbasm\HelloWorld\Model;

class CustomModel
{
    public function __construct(
        private \Magento\Catalog\Model\ProductRepository $productRepository,
        private \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        private \Psr\Log\LoggerInterface $logger
    ) {}
}


				
			

Benefits for Magento 2 Developers

  1. Reduced Boilerplate Code:
    • No need to declare and assign class properties separately.
    • Makes the codebase cleaner and easier to navigate.
  2. Improved Readability:
    • Constructors are more concise, improving the readability of classes.
  3. Less Error-Prone:
    • Avoids potential issues like forgetting to assign a dependency to a property.
  4. Encourages Type-Safe Development:
  • PHP 8 promotes the use of strict typing, which aligns with Magento’s best practices

Use Cases in Magento 2

Model Classes

Magento models often depend on repositories and configuration objects. Constructor property promotion is perfect for these scenarios.

 

				
					<?php
namespace Abbasm\HelloWorld\Model;

class ExampleModel
{
    public function __construct(
        private \Magento\Framework\UrlInterface $urlBuilder,
        private \Magento\Customer\Model\Session $customerSession,
        private \Magento\Framework\Message\ManagerInterface $messageManager
    ) {}
}

				
			

Helper Classes

Helpers, used for utility functions in Magento 2, often rely on injected dependencies like configuration objects or logging utilities.

 

				
					<?php
namespace Abbasm\HelloWorld\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    public function __construct(
        private \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        private \Psr\Log\LoggerInterface $logger
    ) {
        parent::__construct($context);
    }

    public function logMessage(string $message): void
    {
        $this->logger->info($message);
    }
}

				
			

Things to Keep in Mind

  1. Backward Compatibility:
    • If your module needs to support older PHP versions (e.g., PHP 7.4), avoid using Constructor Property Promotion.
  2. Magento Best Practices:
    • Always follow Magento’s DI and type-safe coding practices, even when using promoted properties.
  3. Avoid Overuse:
  • While property promotion is great for simple use cases, avoid overloading constructors with too many dependencies.

Conclusion

PHP 8’s Constructor Property Promotion is a game-changer for Magento 2 developers, especially when working with DI-heavy classes. By reducing boilerplate code and improving readability, this feature streamlines module development while aligning with Magento’s best practices. If you’re using Magento 2.4.4 or later, take advantage of PHP 8 features to write cleaner, more efficient code!

Ready to Simplify Your Code? Upgrade to PHP 8 and enjoy a smoother Magento 2 development experience.
Happy coding! 😊