如何在表模型中获取默认的db 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\''
),
),
);
现在我想拥有
我的albumTable.php中的$this->adapter
我试图接收如下:
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 \ Model \ AlbumTable包含2个抽象方法 因此必须宣布抽象或实施其余的 方法 (Zend的\的ServiceManager \ ServiceLocatorAwareInterface :: setServiceLocator, Zend的\的ServiceManager \ ServiceLocatorAwareInterface :: getServiceLocator) 在
答案 0 :(得分: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');
但是,如果你阅读了入门guide,它解释了如何使用服务管理器工厂构建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);
},
答案 1 :(得分:0)
使用它来创建数据库适配器:
$adapter = $this->getServiceLocator()->get('db');
你可以使用' db'只有在您创建别名时才会这样。您也可以尝试在\ autoload \ config \ local.php中的locals.php中编写内容。 现在,假设我们想在mySQL中执行数据库查询: 创建一个sql statetment并放入变量$ sql。 现在这样做:
$statement = $adapter->createStatement($sql);
$result = $statement->execute();
希望这有帮助。