Just a question, is it a good practice to close connections after opening? I open connections as follows:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();

Magento 2

  • Yes if there is no other query related task, and don’t use object manager in code Jun 26 '20 at 14:11
  • and how do i do that? I tried $resource->closeConnection(); Jun 26 '20 at 14:16

You can close the connection by below example.


Below is the full details for a custom connection without using the object manager.

    protected $_resource;
    public function __construct(      
        \Magento\Framework\App\ResourceConnection $resource
        $this->_resource = $resource;      

    public function execute()
        $connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
        $data = $connection->fetchAll('SELECT * FROM tabel_name');

For more details, you can check this file


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.