-
Notifications
You must be signed in to change notification settings - Fork 9.4k
Description
When running bin/magento setup:di:compile
the process throws an error if in a class receives an instance of an object as a constructor argument that is already contained in the Context
class of the parent.
This enforces coupling custom code to implementation details of the parent classes, however, parent dependencies should be encapsulated.
In my opinion (and I'm sure there are arguments to keep things the way there are, too), enforcing the use of objects from the parent Context
increases coupling in a bad way.
Coupling makes code brittle and rigid. Coupled code is more likely to break during changes (e.g. upgrades).
Even though inheritance is a very strong form of source code dependency in itself, all coupling to the parents implementation should ideally be avoided.
Treating the parent class in the same way as an external collaborator object helps to keep the code maintainable.
I think it would be better to display a warning if a class of a third party module access the Context
object of a parent, contrary to the current compiler behavior.
Preconditions
A Magento 2 instance (any version afaik) with a custom module.
Steps to reproduce
Create a module containing the following class and run the compiler:
<?php
namespace My\Cool\Controller\Foo;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\RedirectFactory;
class Example extends Action
{
/**
* @var RedirectFactory
*/
private $redirectFactory;
public function __construct(Context $context, RedirectFactory $redirectFactory)
{
parent::__construct($context);
$this->redirectFactory = $redirectFactory;
}
public function execute()
{
$result = $this->redirectFactory->create();
$result->setPath('/');
return $result;
}
}
Expected result
The compiler compiles.
Actual result
The compiler raises an error because the RedirectFactory
already is contained in the Magento\Framework\App\Action\Context
instance.
I suggest removing that check from the compiler. If it is required by the core team, it should be moved into a separate command or tool.