获取表模型默认的Zend分贝适配器(Get default zend db adapter in t

2019-11-01 19:07发布

我怎样才能在我的表模型的默认数据库adabter? 我想用它来创建一个事务。

在database.global.php:

    return array(
   'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
        'aliases' => array(
            'db' => 'Zend\Db\Adapter\Adapter',
        ),
    ),
    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=cww;host=localhost',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
        ),
    ),
);

现在,我想有$this->adapter我albumTable.php

我试着接受它如下:

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Update;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Ajax\Model\Album;

class AlbumTable implements ServiceLocatorAwareInterface
{
    protected $tableGateway;
    protected $adapter;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
        $this->adapter  = $this->getServiceLocator()->get('db');    
    }

但我得到的错误:

致命错误:类的Ajax \模型\ AlbumTable包含2种抽象方法,因此必须声明为抽象或实现其余的方法(Zend的\的ServiceManager \ ServiceLocatorAwareInterface :: setServiceLocator,Zend的\的ServiceManager \ ServiceLocatorAwareInterface :: getServiceLocator)在

Answer 1:

添加以下功能:

public function getServiceLocator() {
    return $this->serviceLocator;
}


public function setServiceLocator(Zend\ServiceManager\ServiceLocatorInterface $serviceLocator) {
    $this->serviceLocator= $serviceLocator;
    return $this;
}

然后,你可以这样做:

$this->$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');

但是,如果你读了入门指导解释了如何构建TableGateways使用服务管理器工厂,传入将对DBAdapter等参数,如下所示:

'RoleTableGateway' => function ($sm) {
    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    $resultSetPrototype = new ResultSet();
    $resultSetPrototype->setArrayObjectPrototype(new Role());
    return new TableGateway('role', $dbAdapter, null, $resultSetPrototype);
},


Answer 2:

用它来创建数据库适配器:

$adapter = $this->getServiceLocator()->get('db');

您可以使用“DB”只能作为您所创建的别名。 您也可以尝试在\自动加载\ CONFIG \ local.php在locals.php写的东西。 现在,假设我们要执行MySQL中的数据库查询:创建一个SQL statetment,把变量$ SQL。 现在这样做:

$statement = $adapter->createStatement($sql);
$result = $statement->execute();

希望这可以帮助。



文章来源: Get default zend db adapter in table model