doutenglou6588 2013-10-26 10:44 采纳率: 0%
浏览 40

PHP - 在Zend框架2中处理多个数据库的最佳方法

We are creating a web application using Zend Framework 2 with multiple databases. I have a core database which loads info of all customers. This database contains customer table. The fields of customer table are ::

  1. id
  2. username
  3. password
  4. database_name
  5. customer_name
  6. ...................

When a customers logs in, i have to load his database name from the core database and then make query requests to the database.

I cannot have multiple adapters either, because all customers have their own database which i have to load from customer table of core_db!

I thought i would prefix database name with table name.

I tried this in Module.php:

"CategoryTableGateway" => function ($sm) {
                $dbAdapter = $sm->get("Zend\Db\Adapter\Adapter");
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Category());
                return new TableGateway("databasename.category", $dbAdapter, null, $resultSetPrototype);
            }

I had configured default database in my config\autoload\database.global.php as this:

    'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=core_db;host=localhost',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ),
)

I got a exception like:

Base table or view not found: 1146 Table 'core_db.databasename.category' doesn't exist.

And then, I removed dbname=core_db from config\autoload\database.global.php.

Now, I got another exception like:

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

So how do i handle that situation in Zend Framework 2. I am new to Zend Framework 2.

Edit: I got the solution to my question by myself.

To connect to table of another schema you need to pass TableIdentifier instead of table!

For example,

Instead of:

 $CategoryTableGateway = new TableGateway("category", $dbAdapter, null, $resultSetPrototype);

You have to do:

$CategoryTableIdentifier = new TableIdentifier('category','dbname');
$CategoryTableGateway = new TableGateway($CategoryTableIdentifier, $dbAdapter, null, $resultSetPrototype);

Hope It Works!

  • 写回答

1条回答 默认 最新

  • dongquan8753 2013-10-26 10:47
    关注

    When a customers logs in, i have to load his database name from the core database and then make query requests to the database.

    This is what you are doing wrong.

    Just keep everything in single database, like very e-commerce site in the world does.

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能