Database neutral connection

I am trying to ‘improve’ my code by making it database neutral and to not have configuration details embedded in the code.

I have updated the content of the db.php file to contain the values required for a successful connection to the database. Within the class named yii\db\Connection

I have read elsewhere that all that is required now to establish a database connection is to do the following:

$db = new yii\db\Connection([

‘dsn’ => ‘xx’,

.

.

]);

My first question is how to establish a database neutral (PDO) connection.

The following code fragment:

$conn = new yii\db\connection([

‘dsn’ => ‘stuff’,

]);

results in an error message Fatal error: Uncaught Error: Class ‘yii\db\connection’ not found in …

And, assuming I get past the above, how do I use the already defined connection details in the db.php file ? I have seen references to Yii::$app->db or Yii:app()->db, but no details as to how to use this code successfully. I really do not want to have this ‘configuration’ data in my code.

The following code fragment:

$conn = new \Yii::$app->db ;

Results in an error message

Fatal error: Uncaught Error: Class ‘Yii’ not found in ….

So it seems clear to me I am incorrectly referencing these supposedly generic classes somehow. Any guidance greatly appreciated.

I don’t know without trying myself, but this may be relevant:

Besides the dsn property, you often need to configure username and password. Please refer to yii\db\Connection for the full list of configurable properties.

Info: When you create a DB connection instance, the actual connection to the database is not established until you execute the first SQL or you call the open() method explicitly.

(Use upper case leading “C” in Connection)

I appreciate the response, however your response I don’t think addresse my issue. My objective is NOT to have the configuration data (db connection attribute values) in my code. This data exists in the db.php file and I am wanting the db open process to use this configuration data. Secondly, the syntax error I am reporting relates to missing class defintions. I repeated the test with yii\db\Connection specified, and the result was the same, namely an error message:

Fatal error: Uncaught Error: Class ‘yii\db\Connection’ not found in …

Ok, so I tried this.
The call seems to need this signature:
$conn = new yii\db\Connection([dsn, username, password ]);

Perhaps use params
https://www.yiiframework.com/doc/guide/2.0/en/structure-applications#params

Whilst I appreciate your efforts, I have to say again you are not addressing the error as presented, namely an error message:

Fatal error: Uncaught Error: Class ‘yii\db\Connection’ not found in …

I do not believe that a parameter list that is incomplete or in error is the explanation for the inabaility of PHP to find the specification of the class. And again I would like to repeat, I do NOT want to embed meta data in my code if it can be avoided. I would expect there is a way to leverage the speficication of the db connection attributes that are located in the db.php file. Can I refer you to the section titled “Creating DB Connections” in the page Working with Databases: Database Access Objects | The Definitive Guide to Yii 2.0 | Yii PHP Framework)%3B

Regards
Mike Brice

Perhaps I am not being entirely clear, I am trying to build/run console applications in w windows 10 environment. Perhaps the manner in which I have constructed these cpmponents is not conformant to yii requirements. I will go away and do some more research before I continue this discussion.

Regards
Mike Brice

The question is if or not the db part of the config array is accessible from the app instance.
To look this up in the source would cost me about the same time as elaborating about this in english :upside_down_face:. I guess you will try this yourself.

I have made progress in my story and would like to present my experiences. What I have to say is probably obvious to you and many other readers, however for those of us on a learning curve simple examples are very useful.

My initial problem was that I had not prepared my console bootstrap file correctly. What I am now using is as follows:

<?php
/**
 * Yii console bootstrap file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

defined('YII_DEBUG') or define('YII_DEBUG', true);

require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';

$composerAutoload = [
    __DIR__ . '/../vendor/autoload.php', // in yii2-dev repo
    __DIR__ . '/../../autoload.php',     // installed as a composer binary
];

$config = require __DIR__ . '/config/console.php';

$vendorPath = null;

foreach ($composerAutoload as $autoload) {

    if (file_exists($autoload)) {
        require $autoload;

        $vendorPath = dirname($autoload);

        break;
    }
}

$application = new yii\console\Application($config) ;

if ($vendorPath !== null) {
	
    $application->setVendorPath($vendorPath);
}

$exitCode = $application->run();

exit($exitCode);
?>



The documentation is correct, however it could be a lot clearer/simper in many respects. Like a lot of technical documentation, it provides answers easily found by those who already know the answers, but for those of us finding our way around the yii framework it is less than intuitive I would suggest.

The object represented by the string Yii::$app->db is an instantiaton of the Yii\db\Connection class, fully populated, and ready for use.

If I wish to continue using the yii\db\Connection class together with the yii\db\Command and related classes, then I simply open the connection as follows:

Yii::$app->db->open()

or, with some PDO related attributes defined

Yii::$app->db->open([

PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,

]);

and off I go. If, however, I wish to use the PDO related classes directly, I can extract the necessary connection values as follows:

$dbdsn = Yii::$app->db->dsn;

$dbuser = Yii::$app->db->username;

$dbpass = Yii::$app->db->password;

These are the values defined in the db.php file conventionally located in the config directory, hence achieving my goal of leveraging the meta data defined in the yii framework configuration.

These same values can be used to support usage of any of the available Database Access Objects, such as the mysqli API set.

In my Windows world, I invoke my console application with the following CLI command executed from my application root directory:

php yii.php bam/command Testing ProcessTesting

“bam” is the name of the command controller to be used. This file, named BamController.php is located in the commands subdirectory of my application root directory. “command” is the action to be invoked within the controller module. An empty copy of my BamController.php is as follows:

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use yii\console\Controller;
use yii\console\ExitCode;


class BamController extends Controller
{

    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     * @return int Exit code
     */
     
    public function actionCommand($batchCommand, $batchFunction)
    {
       … application specific code here

        return ExitCode::OK;
    }

}

The values “Testing” and “ProcessTesting” are assigned to the variables $batchCommand and $batchFunction in the function actionCommand.

Hopefully this is useful for others.