1

I recently saw a very helpful post about how to connect to an external database from a Craft plugin and I wanted to confirm I understood the implementation correctly.

On this response the author recommended a way to leverage Yii's Query Builder on external databases. Is the following snippet the way to properly implement this in a service? Do I need to manually "close" this connection or is this alone the way to implement this?

<?php

// Connect to an external database
$db = Craft::createComponent([
    'emulatePrepare'    => true,
    'charset'           => 'utf8',
    'class'             => 'Craft\DbConnection',
    'autoConnect'       => true,
]);

$db->connectionString = 'mysql:host=localhost;dbname=MY_DB;port=3306';
$db->username = 'UN';
$db->password = 'PW';

// Use Query Builder to fetch data from the database
$data = $db->createCommand()
    ->select("*")
    ->from("TBL")
    ->queryAll();

// Pass along the data to be used in a template via variables
return $data;
1
  • 1
    You can see how the Connect plugin does it, if that helps ya. Commented Dec 15, 2018 at 1:58

1 Answer 1

1

If only the service will be connecting to it and only one method, then your example works fine.

If only the service will be connecting to, but you use it across multiple methods, then you might want to move the bootstrapping part to the service init() method and save the database connection as a private instance variable in the service so everything in the service can access it.

Do I need to manually "close" this connection

I wouldn't worry about it.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.