2013-03-14 72 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(); 

希望這會有所幫助。