Difference Between ResourceConnection and Resource in Magento 2

magento2

I'm trying to make direct sql queries. In CustomBlock.php I have the following:

namespace My\AdminSample\Block\Adminhtml;

use Magento\Backend\Block\Template;
use My\AdminSample\Helper\ConfigHelper;
use My\AdminSample\Model\AdminSample;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;

class CustomBlock extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \My\AdminSample\Helper\ConfigHelper
     */
    protected $_config;

    protected $_adminSampleModel;

    protected $_resource;

    protected $connection;

    /**
    * @param Context $context
    * @param array $data
    */
    public function __construct(
        // \Magento\Framework\App\ResourceConnection $resource,
        \Magento\Framework\App\Resource $resource,
        \Magento\Framework\Registry $registry,
        Template\Context $context,
        AdminSample $adminSampleModel,
        ConfigHelper $config,
        array $data = []
        ) {
        $this->_resource = $resource;
        $this->_coreRegistry = $registry;

        $this->_config = $config;
        $this->_adminSampleModel = $adminSampleModel;
        parent::__construct($context, $data);
    }

    public function getConnection()
    {
        if (!$this->connection) {
            $this->connection = $this->_resource->getConnection('core_write');
        }
        return $this->connection;
    }
    public function getDirectQuery()
    {
        $table  = $this->_resource->getTableName('table_name_here'); 
        $sku    = $this->getConnection()->fetchRow('SELECT * FROM `'.$table.'`');
        return $sku;
    }

Now if I comment:

\Magento\Framework\App\ResourceConnection $resource,

i receive

Invalid block type: My\AdminSample\Block\Adminhtml\CustomBlock

but if i comment

\Magento\Framework\App\Resource $resource,

the result is

Notice: Array to string conversion in
/public_html/vendor/magento/framework/HTTP/PhpEnvironment/Response.php
on line 54

Best Answer

Magento\Framework\App\Resource and \Magento\Framework\App\ResourceConnection it's the same classes. Magento\Framework\App\Resource was renamed to \Magento\Framework\App\ResourceConnection in Magento 2.0 to support php 7.0.

Related Topic