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

Connection adapter does not update in model layer

Hi.

I have a model class which inherits from a base model class. Inside my base model class I have an initialize() method with the following instruction:

public function initialize()
{
    $this->setConnectionService('myAdapterWrite');
}

The thing is, in all my other classes that inherit from the base model class I am overwriting this initialize() method with another adapter and the connection seems to keep the first adapter at all. I mean, it does not change the adapter. It just set up the adapter at the first time. When debuging, I realized that the initialize() is called just once. Hence, when I try changing the adapter it does not connect to the other database I need.

I am sorry if I did not make myself clear.

Does it have any solution?

Thanks in any advance.

edited Sep '17

The initialize() method is only called if the beforeExecuteRoute event is executed with success. This avoid that application logic in the initializer cannot be executed without authorization.

So,

If you want to execute some initialization logic just after the controller object is constructed then you can implement the onConstruct() method:

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function onConstruct()
    {
        // just like raw PHP construrctor
    }
}

https://docs.phalcon.io/en/3.2/controllers#initializing

Hi @stamster, thanks for the reply.

I've tried onConstruct, but it simply changes the adapter settings, it does not redo the connection to the new database as expected.

Any idea how to do it?

What is your goal with this? Setting different connection per specific model / class?

edited Sep '17

I have different databases for each client.

And I'm running Phalcon/Cli operations that change data for multiple clients, so I need to redo the connection to the database for each client in the queue. @stamster