Skip to content

Magento 2 add custom logic in resource model as per Adobe recommendations

We have a adobe recommendation i.e move the custom queries to resource model. followed below steps but while executing getting the below error

Fatal error: Uncaught Error: Call to a member function getConnection() on null in vendor/magento/framework/Model/ResourceModel/Db/AbstractDb.php:312

I have added my logic in the app/code/Demo/OrderStatus/Model/ResouceModel/ChangedOrderStatus.php but getting above error while executing this file can any one advise how to fix?

<?php
/**
 * Copyright © demo, Inc. All rights reserved.
 */
namespace DemoOrderStatusModelResourceModel;

use DemoOrderStatusModelConfigData as ConfigData;
use DemoOrderStatusModelLoggerLogger;

class ChangedOrderStatus extends MagentoFrameworkModelResourceModelDbAbstractDb
{
    /**
     * @var Logger
     */
    protected $logger;

    /**
     * Define main table
     */
    protected function _construct()
    {
        $this->_init('demo_table', 'entity_id');
    }

    /**
     * @param Logger $logger
     */
    public function __construct(
        Logger $logger
    ) {
        $this->logger = $logger;
    }

    /**
     * Remove record
     */
    public function removeRecord()
    {
        try {
            $connection = $this->getConnection();
            $tableName = $connection->getTableName(ConfigData::ORDER_STATUS_TABLE);
            $status = ConfigData::EXECUTED;
            $connection->delete(
                $tableName,
                ['status = ?' => $status]
            );
        } catch (Exception $exception) {
            $this->logger->error($exception->getMessage());
        }
    }
}