Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly initialize database connection in Phalcon

at the moment, I initialize database in following way:

$di->set('db', function() use ($config){
    return new \Phalcon\Db\Adapter\Pdo\Mysql(
        array(
            "host" => $config->database->host,
            "username" => $config->database->username,
            "password" => $config->database->password,
            "dbname" => $config->database->name
        )
    );
});

but when mysql credentials are wrong, or database doesn't exist, Phalcon returns blank page without any error message. Such situations are real headache, because small error in login/password/host causes almost untraceable error.

I think that Pdo constructor stops PHP code execution in this case.

So how do you initialize database connection in Phalcon when you want website to tell you about problem with database?

like image 770
lot Avatar asked Aug 13 '14 12:08

lot


3 Answers

I ended with following code:

$di->set('db', function() use ($config){
    try {
        $db = new \Phalcon\Db\Adapter\Pdo\Mysql(
            array(
                "host" => $config->database->host,
                "username" => $config->database->username,
                "password" => $config->database->password,
                "dbname" => $config->database->name
            )
        );
    } catch (Exception $e) {
        die("<b>Error when initializing database connection:</b> " . $e->getMessage());
    }
    return $db;
});

Please tell me if there is a better way.

like image 86
lot Avatar answered Oct 02 '22 02:10

lot


I use this configuration:

$di->set('db', function () use ($config) {
        $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => $config->database->host,
            "username" => $config->database->username,
            "password" => $config->database->password,
            "dbname" => $config->database->dbname,
            "options" => array(
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
            )
        ));
        if (APPLICATION_ENV == 'development') {
            $eventsManager = new Phalcon\Events\Manager();
            $logger = new Phalcon\Logger\Adapter\File($config->application->logsDir . "sql_debug.log");
            //Listen all the database events
            $eventsManager->attach('db', function ($event, $connection) use ($logger) {
                if ($event->getType() == 'beforeQuery') {
                    $logger->log($connection->getSQLStatement(), Logger::INFO);
                }
            });
            //Assign the eventsManager to the db adapter instance
            $connection->setEventsManager($eventsManager);
        }
        return $connection;
    }, true);

there is one more option for utf8 and if application enviroment is development, it logs all the sql calls to sql_debug.log. You can see, that I'm using $config, its defined like this:

switch (APPLICATION_ENV) {
        case 'development':
            $config = new Phalcon\Config\Adapter\Ini(__DIR__ . '/../app/config/config_dev.ini');
            break;
        case 'testing':
            $config = new Phalcon\Config\Adapter\Ini(__DIR__ . '/../app/config/config_test.ini');
            break;
        case 'production':
            $config = new Phalcon\Config\Adapter\Ini(__DIR__ . '/../app/config/config_production.ini');
            break;
    }

and in config file you would find something like this:

[database]
adapter = Mysql
host = localhost
username = root
password =
dbname = db_name
like image 42
Lukas Liesis Avatar answered Oct 02 '22 01:10

Lukas Liesis


You can make it more general. Sou you can catch all the errors that may occur and display them nicely. I'm using below bootstrap file (config) for developement as described here.

<?php

error_reporting(-1);

$debug = new Phalcon\Debug();
$debug->listen();

/** Read the configuration */
$config = include __DIR__ . '/../config/config.php';

/** Read auto-loader */
include __DIR__ . "/../app/config/loader.php";

/** Read services */
include __DIR__ . "/../app/config/mvc/services.dev.php";

/** Handle the request */
$application = new \Phalcon\Mvc\Application();
$application->setDI($di);
if (!empty($_SERVER['REQUEST_URI'])) {
    $uriParts = explode('?', $_SERVER['REQUEST_URI']);
    $uri = $uriParts[0];
} else {
    $uri = '/';
}
echo $application->handle($uri)->getContent();

Which concludes that interesting part is here:

$debug = new Phalcon\Debug();
$debug->listen();
like image 27
jodator Avatar answered Oct 02 '22 02:10

jodator