Good way to connect database in Phalcon php framework

Database connection settings can be done by registering services in the container.
Here is how we can connect a postgresql database

use Phalcon\DI;
    use Phalcon\Db\Adapter\Pdo\Postgresql as DbAdapter;
    
    /** 
    * We can move this config is a separate config file 
    */
    $config = new \Phalcon\Config(array(
        'database'      => array(
            'adapter'  => 'Postgresql',
            'host'     => "localhost",
            'username' => "dbuser",
            'password' => "dbpass",
            'dbname'   => "dbnam"
        )
    ));

    /**
    * Dependency Injector, this can be Di() or FactoryDefault()
    */
    $di = new Di();
    
    /** 
    * Create a 'Shared' service so new object will not created every time we call
    */
    $di->setShared('db', function () use ($config) {

      return new DbAdapter(array(
        'host'     => $config->database->host,
        'username' => $config->database->username,
        'password' => $config->database->password,
        'dbname'   => $config->database->dbname
      ));
    });

Posted

in

,

by

Tags: