I need to convert some singleton method calls from Magento 1 to Magento 2. Specifically Mage::getSingleton('core/resource')->getConnection($type); How can I do this in M2? I know that I should first instantiate object manager, but everything after that is to me unknown. Any advice?


Not recommended but short Magento 2 alternative:


Recommended and common approach:

Add Magento\Framework\App\ResourceConnection as a dependency to constructor of class where you need to use it, assign it to property and then use property to get connection.

public function __construct(\Magento\Framework\App\ResourceConnection $resourceConnection)
    $this->resourceConnection = $resourceConnection;

public function doSmth()

Magento\Framework\App\ResourceConnection resource connection for M2 for both read/write.

public function __construct(
    \Magento\Framework\App\ResourceConnection $resourceConnection
) {
   $this->resourceConnection = $resourceConnection;

Use following way:

$connection = $this->resourceConnection->getConnection();
$sql = "SELECT increment_id FROM sales_shipment WHERE order_id = '$orderId'";
$result = $connection->fetchAll($sql);
  • I have this error when I try to create the ResourceConnection: Argument 1 passed to Magento\Framework\App\ResourceConnection::__construct() must be an instance of Magento\Framework\App\ResourceConnection\ConfigInterface, none given – Vladimir Despotovic Mar 16 '17 at 16:29
  • What is your magento version? – Sohel Rana Mar 16 '17 at 16:31
  • Do you create the instance of your actual class by new operator? – Sergii Ivashchenko Mar 16 '17 at 16:51
  • Yes, I used "new" keyword to create it. – Vladimir Despotovic Mar 17 '17 at 8:51
  • 1
    @VladimirDespotovic don't use "new", Always use DI. – Sohel Rana Mar 17 '17 at 9:46

I have solved this by using:

$om = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER) -> getObjectManager();
$rc = $om->get("\Magento\Framework\App\ResourceConnection");
  • 1
    Could you expand your answer a bit more? At least include the line that defines $om – 7ochem Mar 17 '17 at 9:44
  • Yes and I will also accept it. As soon as SO allows. – Vladimir Despotovic Mar 17 '17 at 9:45
  • this feels dirty, are you sure this is Magento's recommended/verified way of calling it? – treyBake Nov 20 '17 at 16:23
  • This is a good way to get a singleton, yes. – Vladimir Despotovic Nov 22 '17 at 21:03

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.