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

How to check dB connection

RU: Здравствуйте. Хотелось бы узнать, возможно ли в Phalcon как-то проверить коннект к базе. Т.е если коннекта к базе нет, то вернуть false, если есть, то true.

EN: Hello. I would like to know, is it possible in Phalcon to check the connection to the database. Ie if the connection to the database, then return false, if there is, it is true.

Thnx.

edited Jul '17

I've extended the default adapter class:

use Phalcon\Db\Adapter\Pdo\Mysql as PhalconMysql;

class MysqlCustom extends PhalconMysql
{
    public function isConnected() {
        try {
            $this->fetchAll('SELECT 1');
        } catch (\Exception $e) {
            if (strpos($e->getMessage(), 'MySQL server has gone away') !== false) {
                $this->connect();
                return true;
            }
            return false;
        }
        return true;
    }
}

Don't forget to initialize this custom class instead of the default in your services!

Usage inside a controller:

class SomeController {
    public function indexAction() {
        echo $this->db->isConnected() ? 'connected!' : 'db is offline!';
    }
}

Did as you said, but it is somehow even does not throw an exception in case of unsuccessful connection.

edited Jul '17

That code only runs once, when you first access the db service.

Create the class that i've pasted above somewhere in your namespace (it has to be autoloaded), then instantiate it in the services like this:

use My\Custom\DbAdapter; // this class is the one i've pasted above

$di->setShared('db', function() {
    $config = $this->getConfig();
    $class = new DbAdapter($config->database->toArray());
    return $class;
});

Then, in a ServiceAware context (like Controllers or Tasks), you can do this:

class MyController extends \Phalcon\Mvc\Controller {
    public function indexAction() {
        echo $this->db->isConnected() ? 'true' : 'false';
    }
}