Dynamic database connections with Zend

The result that I am trying to achieve includes the presence of an application with a database with minimal tables that store data about users in the system, this database will be used to check the login information when entering the application. I want to be able to dynamically connect to another database after a user logs in based on the information stored about that user in the main database.

Basically, I want each user in the system to have his own database, connect to this database after logging in and be able to use the common db model classes (since each user db will have the same tables as every other user db).

Is it possible? And if so, how would I implement a dynamic db connection (say, in an action that checks their login details).

Any help would be greatly appreciated.

+3
source share
2 answers

The simplest answer is not to make a second connection, but simply to change the default scheme after determining the name that this user needs.

For example, enter the secondary db name for this user:

$db = Zend_Db::factory(...options...);
$secondary_db = $db->query("SELECT secondary_db 
    FROM user_data WHERE user = ?", $userid)
   ->fetchOne();

Then run the query to change the schema. Please note that the statement USEdoes not support the prepared statement, so you need to execute it using the driver API:

$db->getConnection()->query("use $secondary_db");

, , . , Zend_Db ..

USE , , . , , .

+1

, . , , , , , Db_Manager. , ... :

public function loginAction()
{
   $request = $this->getRequest();
   $user = $request->getParam('username');
   $pass = $request->getParam('password');

   $auth = new My_Auth_Adapter($user, $pass);
   $authResult = Zend_Auth::getInstance()->authenticate($auth);

   if($authResult->isValid()){
      My_Db_Manager::connectForUser($authResult->getIdentity());
   }
}

, , db . , .

+1

Source: https://habr.com/ru/post/1769077/


All Articles