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

Diffrent databases rest

Hey everbody,

I'm developing a Rest application with a micro setup plus collections to structure the logic. In every Rest Uri I get the database plus the id or whatever is needed for the function. Example:

GET /api/search/exampleModel/id+exampleDB

How should I handle the connection to the diffrent databases?

Idea:

1 Set the dbs:

$di->set('dbExample', function(){ return new PdoMysql(array( "host" => "localhost", "username" => "", "password" => "", "dbname" => "" )); });

2 Create function in model:

public function changeDb($db) { $this->setConnectionService($db); }

3 Create object of the model inside the controller and change db:

$myModell = new ExampleModell(); $myModell->changeDb("dbExample");

Is there a better way to handle this situation?

Bruno

  • I use phalcon dev tools to generate model in own directory, Database cms in directory ../app/models/cms
  • In model files add namespace Cms; and
    public function initialize()
    {
        // By default "db" is choose for phalcon, you may specify other connection in your
        $this->setConnectionService("dbCms");
    }
  • index.php add
    $config = new Phalcon\Config\Adapter\Ini(__DIR__ . "/../app/config/config.ini");

    $di = new Phalcon\DI\FactoryDefault;
    $di->set('dbCms', function () use ($config) {
        return new Phalcon\Db\Adapter\Pdo\Mysql(
            [
                "host" => $config->dbCms->host,
                "username" => $config->dbCms->username,
                "password" => $config->dbCms->password,
                "dbname" => $config->dbCms->dbname,
                "options" => [
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
                    PDO::ATTR_CASE => PDO::CASE_LOWER,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                ],
            ]);
    });

    $loader = new Phalcon\Loader;
    $loader->registerNamespaces([
        'Cms' => $config->phalcon->modelsCmsDir,
    ]);

now your code is something like $myModell = new Cms\ExampleModell(); Hope this help.