2013-03-14 71 views
0

如何在我的表模型中获取默认的db adabter?我想用它来创建一个事务。在表模型中获取默认的zend db适配器

在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');  
    } 

但我得到的错误:

Fatal error: Class Ajax\Model\AlbumTable contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator, Zend\ServiceManager\ServiceLocatorAwareInterface::getServiceLocator) in

回答

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); 
}, 
+0

感谢您的回答。我已经设置了tableGetaway,所以我现在用这个来获取我需要的'$ this-> tableGateway-> getAdapter()';这是我所需要的:)谢谢反正 – directory 2013-03-14 16:59:46

+0

我得到了这个错误“致命的错误:调用成员函数get()在一个非对象在F:\ xampp \ htdocs \ zendtest \模块\应用程序\ src \应用程序\模型\ Signup.php第41行“。请参阅我的问题”http://stackoverflow.com/questions/20319388/calling-adapter-in-model“,是您的解决方案适合我的情况? – user1844626 2013-12-02 03:41:01

+0

您需要手动将服务定位器或数据库适配器设置到您的模型类中。对这些问题的评论应提供指导。 – 2013-12-02 08:54:19

0

使用它创建数据库适配器r:

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

只有在创建别名时才能使用'db'。你也可以尝试在\ autoload \ config \ local.php中的locals.php中写东西。 现在,假设我们想在mySQL中执行一个数据库查询: 创建一个sql语句并放入变量$ sql。 现在这样做:

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

希望这会有所帮助。