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

Unable to set parameter `options` when creating PDO object from config object

As Phalcon\Config converts all arrays to objects Phalcon\Config, so we can't use key options in this case. Just getting this error: TypeError: PDO::__construct() expects parameter 4 to be array, object given

I think it should be fixed.

P.S. I'm using Phalcon 4.

Can you show us how are you setting the connection?

Sample code i have been using for a while:

        $di->setShared('db', function() use ($databaseCredentials) {
            return new \Phalcon\Db\Adapter\Pdo\Mysql([
                'host' => $databaseCredentials->host,
                'username' => $databaseCredentials->username,
                'password' => $databaseCredentials->password,
                'dbname' => $databaseCredentials->name,
                'charset' => 'utf8',
                'options'  => [
                    \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8, CHARACTER SET utf8;',
                    \PDO::ATTR_PERSISTENT => true,
                    \PDO::ATTR_STRINGIFY_FETCHES => false
                ]
            ]);
        })


2.0k

Your code works because you use an array as config. In my case i use config object:

$config = \Phalcon\Config([
   'database' => [
      'adapter' => 'Mysql',
      'host' => 'localhost',
      'username' => 'user',
      'password' => 'pass',
      'dbname' => 'db_name,
      'charset' => 'utf8mb4',
      'options' => [],
  ]
]);

$di->set(
   'dbMaster',
   function() use ($config) {
      return new \Phalcon\Db\Adapter\Pdo\Mysql((array) $config->database);
   }
);

As we see, i should use the trick (array) $config->database which converts object to array, but it doesn't converts nested arrays. My miss when created this post, here is a little bit another problem.

I don't remember where i've found such method, i tried this few years ago with Phalcon 3 and now came back to Phalcon, but now it is version 4 :)

I think all config parameters should be in a separate file, we should prevent to set it in working scripts. I can use recursive converting, but i'm not sure it is the right way.



145.0k
Accepted
answer

There is method toArray()



2.0k

That works, thank you.