0

I have a collection.php file. I am adding some function into that which calls other models.As per Magento 2 first we have to add object managerger interface. And then we can call other model.like below :

$this->_objectManger('\Namespace\Module\Model\Customfile')->functionName();

To use $this->_objectManger we have to define in __Construct first. Now I am doing same thing in __Construct method of Collection.php file. But it is not working and creating issues.

Please check code : Collection.php

<?php
namespace \Namespace\Module\Model\ResourceModel\Testfile;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{

 public function __construct(
    **\Magento\Framework\ObjectManagerInterface $objectManager,** 
    \Magento\Framework\Data\Collection\EntityFactory $entityFactory,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
    \Magento\Framework\Event\ManagerInterface $eventManager,
    \Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory $optionValueCollectionFactory,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
    \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
) {
    $this->_optionValueCollectionFactory = $optionValueCollectionFactory;
    $this->_storeManager = $storeManager;
    parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
    $this->logger = $logger; 
    $this->_objectManager = $objectManager;
 }

How to add extra classes in this ? Please explain where I am wrong and why.

  • @ Krupali Please share the error you are getting. – Krishna ijjada Jun 22 '16 at 11:16
0

Please explain where I am wrong and why.

You should not require the object manager itself as dependency in the constructor, instead require the object you need directly:

public function __construct(
    ...,
    \Namespace\Module\Model\Customfile $customfile
) {
    ...
    $this->customfile = $customfile;
}

Then use it like this:

$this->customfile->functionName();

This will use a shared instance of the Customfile model (like a singleton in Magento 1). If you need a new instance every time, you can use the automatically generated factory.

With Factory:

public function __construct(
    ...,
    \Namespace\Module\Model\CustomfileFactory $customfileFactory
) {
    ...
    $this->customfileFactory = $customfileFactory;
}

Usage:

$customfile = $this->customFileFactory->create();
$customfile->functionName();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.