在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帶來的誤差。
看起來像我的方法是錯誤的。
非常感謝提前。
感謝您的回答。我試過這個代碼。 – TMisiunas
看起來我的問題不是很確切。 – TMisiunas