At this time I am annoyed of writing similar constructors en masse like the following within my modules.
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
/* ... */
\Foo\Bar\Model\Baz $baz,
/* ... */
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
$this->registry = $registry;
/* ... */
$this->baz = $baz;
/* ... */
/* some awesome stuff */
}
In many many many cases I need instances of the same classes all over my module.
So I was questioning myself, if it would be an acceptable way to use one or two central helper classes, which provide the necessary classes, instead of defining them in every single constructor.
This means a pattern like this:
Helper Class
namespace Foo\Bar\Helper
class Main
{
protected $baz;
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
/* ... */
\Foo\Bar\Model\Baz $baz,
/* ... */
) {
$this->registry = $registry;
/* ... */
$this->baz = $baz;
/* ... */
/* some awesome stuff */
}
public function getBazInstance()
{
return $this->baz;
}
}
The shorter constructor
public function __construct(
\Foo\Bar\Helper\Main $mainHelper,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
$this->mainHelper = $mainHelper;
/* some awesome stuff */
}
At this point I am not sure if I will have to deal with big disadvantages in future caused by this structure. Would this be an acceptable way to reduce the amount of DI definitions?
my biggest point is the amount of helpers I have to use (my own and core helpers) the Context classes seemed to me to do exactly what you said, I was just not sure.
thx 4 advice
– bukart Sep 01 '16 at 06:47ContextClasses are Magento classes that encompass entire sections of Magento? i.e. Category Context, will help manage Add/Edit/Remove/View of Categories without the need of importing multiple classes to do the same action? – MackieeE Apr 10 '17 at 09:06\Magento\Catalog\Model\Category, you'll see that it is including the same\Magento\Framework\Model\ContextI mentioned--there's actually nothing in there about categories at all. You're looking for a repository--take a look at\Magento\Catalog\Api\CategoryRepositoryInterface. – Ryan Hoerr Apr 10 '17 at 12:56