We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

FactoryDefault DB Availability

Upfront, let me say that I am not using PHQL for this application.

I am trying to understand how to access the db connection in a model within an app that is using FactoryDefault for DI.

The code from services.php is shown below.

/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function() use ($config) {
    $dbclass = 'Phalcon\Db\Adapter\Pdo\\' . $config->database->adapter;
    return new $dbclass(array(
        "host"     => $config->database->host,
        "username" => $config->database->username,
        "password" => $config->database->password,
        "dbname"   => $config->database->name
    ));
});


2.7k

Hi. I not sure about what you want, but to access DI you can try use:

$this->getDI()

or

\Phalcon\DI\FactoryDefault::getDefault()

That works wekk actually! Thank you! One thing that remains a mystery:

$di = \Phalcon\DI\FactoryDefault::getDefault();

$dbConn = $di["db"];

I am getting a mystery error on the $dbConn line.

"Something went wrong, if the error continue please contact us" I can't seem to get the real error to print out; so I can't tell why that reference fails.



7.3k
Accepted
answer

Two issues lead to this sad state of affairs: 1) wrong db hostname. 2) Invo has an eventmanager NotFoundPlugin plugin that displays a an error page instead of a literal error. This is am reviewing...

Thanks for the assist hvjohny!