ZF2 Re-starting service manager key

2019-05-26 13:07发布

问题:

I have a database adapter stored in my service manager called "dbAdapter". I am looking for a way to disconnect and then re-connect to this adapter using a slightly different configuration, possibly several times.

The reason is that I have many customers who's database structure is 100% is the same. I am writing a cron job that will do maintance on each database but it has to connect to the first one, do its thing, drop the connection and connect to the next one...until it is out of databases.

I was looking through the source but I could only find a single protected method in Zend\ServiceManager\ServiceManager.php called unregisterService which looks like it would do what I want but it is a protected method and thus I can't call it from my controller.

Is it possible to "expire" a service manager key and force it to re-create it on its next call?

回答1:

You could set $allowOverride to true in the ServiceManager and then register a null value under the name dbAdapter.

$serviceManager->setAllowOverride(true)
               ->setService('dbAdapter', null)
               ->setAllowOverride(false);