2013-08-19 38 views
1

在ZF2項目中,我創建了自定義庫供應商/ TestVendor/TestLibrary /。 在這個庫中,我想創建2個類:TestClass和TestClassTable。 TestClass應該實例化我的自定義對象,TestClassTable應該處理數據庫和表。 我需要使用類TestClass表中的DBAdapter來訪問數據庫和表。Zend Framework 2:如何在自定義庫中獲得DBAdapter

的代碼看起來是這樣的:

在模塊索引控制器I從識別TestClass創建對象

類的TestController延伸AbstractActionController {

$TestObject = $this->getServiceLocator()->get('TestClass'); 

}

以我的自定義類的供應商/TestVendor/TestLibrary/TestClass.php我創建了一些方法:

namespace TestVendor \ TestLibrary;

類識別TestClass {

protected $Id; 
protected $Name; 

function __construct(){} 

public function doMethodOne() { 
    $TestClassTable = new TestClassTable(); 
$this->Id = 1; 
$TestObjectRow = $TestClassTable->getTestObjectById($this->Id); 
$this->Name = $TestObjectRow['Name']; 
return $this; 
} 

}

而在TestClassTable類我要訪問數據庫

命名空間TestVendor \ TestLibrary;

使用Zend \ Db \ TableGateway \ AbstractTableGateway;

類TestClassTable擴展AbstractTableGateway {

public function __construct() { 

    $this->table = 'table_name'; 
    $this->adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'); 

} 

public function getTestObjectById($Id) { 

    $Id = (int) $Id; 
    $rowset = $this->select(array('id' => $Id)); 
    $row = $rowset->current(); 
    return $row; 
} 

}

當然試圖訪問服務定位器或數據庫適配器在我班TestClassTable帶來的誤差。

看起來像我的方法是錯誤的。

非常感謝提前。

回答

0

您應該使用服務管理器將它注入到您的課程中。

服務管理器配置:

return array(
    'factories' => array(
     'MyClass' => function($sm) { 
      $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
      $myClass = new \MyNamespace\MyClass($dbAdapter); 
      // I would have a setter, and inject like that but 
      // using the constructor is fine too 
      //$myclass->setDbAdapter($dbAdapter); 

      return $myClass; 
     }, 
    ) 
) 

現在你可以抓住一個實例的控制器內,與已注入你的數據庫適配器:

SomeController.php

public function indexAction() 
{ 
    $MyObject = $this->getServiceLocator()->get('MyClass'); 
} 
+0

感謝您的回答。我試過這個代碼。 – TMisiunas

+0

看起來我的問題不是很確切。 – TMisiunas

1

如果您手動注入DBAdapter你的代碼是高度耦合的,使用服務管理器可以幫助你,但是你仍然將自己耦合到DBAdapter。有多種方法可以從您的供應商代碼中取消耦合,具體取決於您嘗試實現的目標。看看數據映射器模式 & 適配器模式 - 與服務經理作爲@Andrew建議。

注意:在ZF2中的供應商庫應該是一個單獨的項目&包括通過作曲家。

相關問題