Drupal 7 db_set_active() in mymodule_init()?
I am trying to change which DB connection to used based on several conditions inside a custom module hook, aptly named mymodule_init()
hook_init() seemed a logical place to put this functionality because it's called so early in the bootstrap game, before any DB queries???
So I have several connections in a pool and which one is used is determined by the module. For the life of I can't get the system to persist the DB - seems to be resetting itself back to 'default' after this hook is executed. Searching the codebase has little effect as well only one or two calls to db_set开发者_JAVA百科_active() are made.
ANy ideas? What hook should I override to change the DB connection at runtime before any DB activity has be done???
Cheers, Alex
Hardly is hook_init
"early in the game" and certainly not the first to fire database queries. The bootstrap order is: load configuration, try to serve the page from cache, initialize the database, load variables, load session, page header. The first hook to fire is hook_boot
either if the page cache has a hit or in page header -- by then at least the variable init phase have fired a query either to load the variables from the database (or to retrieve them from cache but you can't rely on cache and the default cache is database anyways). All is not lost, however. You can either put your code right in settings.php
or write a small cache handler, something like this:
class HackyDatabaseCache extends DrupalDatabaseCache {
function __construct($bin) {
// your code finding the database here.
parent::__construct($bin);
}
}
add $conf['cache_backends'][] = 'path/to/hackydatabasecache.inc';
and $conf['cache_class_cache_page'] = 'HackyDatabaseCache';
to your settings.php
. This will make sure your code fires before any queries. If you are using memcache or mongodb for caching, then extend that with the same code just change which class is extended.
精彩评论