I'm working on learning Magento 2, and I'm having issues with the automatic constructor dependency injection in my resource model collection.
Here is my code:
namespace TylerSchade\Contacts\Model\ResourceModel\Contact;
use \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected $session;
public function __construct(
\Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource,
\Magento\Customer\Model\Session $session,
\Magento\Framework\DB\Adapter\AdapterInterface $connection = null
) {
$this->session = $session;
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
}
protected function _construct()
{
$this->_init('TylerSchade\Contacts\Model\Contact', 'TylerSchade\Contacts\Model\ResourceModel\Contact');
}
public function addCustomerFilter()
{
$this->addFieldToFilter('customer_id', $this->session->getCustomerId());
}
}
When I run code that loads the collection, I receive the following error:
Fatal error: Uncaught Error: Cannot instantiate interface Magento\Framework\DB\Adapter\AdapterInterface in /var/www/magentotwo/magentotwo/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php on line 73
I've tried to reorder the parameters and specify the parameter that causes the error to a default of null, because I've seen that in core code, but that leads to more errors. I've also tried to add a di.xml file that specified the preference for the interface to Magento\Framework\DB\Adapter\Pdo\Mysql
, thinking that perhaps the issue is that I haven't specified a preference for the interface, but then I receive the following errors:
2 exception(s):
Exception #0 (InvalidArgumentException): Configuration array must have a key for 'dbname' that names the database instance
Exception #1 (Zend_Db_Adapter_Exception): Configuration array must have a key for 'dbname' that names the database instance
How can I fix these errors? Also, can you help me better understand the object manager's constructor dependency injection to avoid errors like this in the future?