我想在Zend Framework 2中设置DB ADAPTER,就像Zend Framework 1中的DB ADAPTER一样。
IN ZF1 bootstrap.php我
protected function _initDatabase() {
$this->bootstrap('db');
$dbResource = $this->getResource('db');
Zend_Registry::set(ESIGN_REGISTRY_KEY_DB, $dbResource);
}
并在application.ini
中resources.db.adapter = "pdo_mysql"
resources.db.params.dbname = "DB NAME"
resources.db.params.host = "HOST"
resources.db.params.username = "DB USER"
resources.db.params.password = "DB PASSWORD"
在我的应用程序中,我可以使用
$dbAdapter = Zend_Registry::get('db');
获取DB ADAPTER。
请帮我在ZF2中配置它。 感谢。
答案 0 :(得分:0)
有几种方法可以做到这一点,这取决于您如何真正构建应用程序。但以下是假设您已在配置文件中为数据库适配器正确设置了所有内容。
所以你可以在某处做到这一点,
use Zend\Db\TableGateway\Feature\GlobalAdapterFeature;
// note, $sm is the service manager here
GlobalAdapterFeature::setStaticAdapter($sm->get('adapter_alias_name'));
您的配置文件中设置了alias
,如:
// both of these are from factories in the `service manager` key in the config file.
'aliases' => array(
'adapter_alias_name1' => 'Zend\Db\Adapter\Adapter1',
'adapter_alias_name2' => 'Zend\Db\Adapter\Adapter2',
)
无论如何,继续,获取您将使用的静态适配器:
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::getStaticAdapter();
这可能就是您所需要的,但您也可以创建一个模型可以扩展的类,其中包含db适配器。
例如:
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\TableGateway\Feature\RowGatewayFeature;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\TableGateway\Feature;
abstract class AbstractTable extends AbstractTableGateway
{
public function __construct()
{
$this->featureSet = new Feature\FeatureSet();
$this->featureSet->addFeature(new Feature\GlobalAdapterFeature());
$this->featureSet->addFeature(new Feature\RowGatewayFeature($this->primary));
$this->featureSet->setTableGateway($this);
$this->featureSet->apply('preInitialize', array());
// view your adapter settings
echo '<pre>' . print_r($this->adapter, true) . '</pre>;die;
}
}
然后你的模型可以扩展该类,并且已经设置了适配器。希望这有意义,并帮助一些。我已经看到过这种方式有很多不同的方式。