Maks3w является правильным, а также кратким.
Подробнее.
Существует множество способов использования вашего Application_Model_DbTable_Employee
для доступа к вашей таблице tab_employee
вашей базы данных.
Самый простой способ для запроса непосредственно из самой dbTable
модели:
class Application_Model_DbTable_Employee extends Zend_Db_Table_Abstract
{
protected $_name = 'tab_employee';
public function selectAllEmployees()
{
//$this refers to the current dbTable object
$select = $this->select();
//when querying from the dbTable the from() parameter is assumed to be $this->_name, array('*')
//there several other sql commands available to the select(), where(), orWhere(), join()
$select->order('id DESC');
$result = $this->fetchAll($select);
return $result;
}
}
контроллер код:
public function indexAction(){
model = new Application_Model_DbTable_Employee();
$employees = $model->selectAllEmployees();
$this->view->employees = $employees
}
Часто модель картографа используется для доступа к базе данных и предоставлять данные на сущность. Это также очень распространено относительно просто. Ключевой пункт, чтобы помнить при проектировании картографа должен включать код для доступа к модели dbTable в качестве адаптера базы данных, которую часто называют gateway
, вот несколько примеров коды:
<?php
//This is one way to build a mapper
abstract class My_Model_Mapper_Abstract
{
/**
* Instance of Zend_Db_Table_Abstract
*/
protected $tableGateway = null;
/**
* Will accept a DbTable model passed or will instantiate
* a Zend_Db_Table_Abstract object from table name.
*/
public function __construct(Zend_Db_Table_Abstract $tableGateway = null)
{
if (is_null($tableGateway)) {
$this->tableGateway = new Zend_Db_Table($this->_tableName);
} else {
$this->tableGateway = $tableGateway;
}
}
/**
* Get default database table adapter
*/
protected function getGateway()
{
return $this->tableGateway;
}
/**
* findAll() is a proxy for the fetchAll() method and returns
* an array of entity objects.
*
* @param $where, primary key id
* @param string $order in the format of 'column ASC'
* @return array of entity objects
*/
public function findAll($where = null, $order = null)
{
$select = $this->getGateway()->select();
if (!is_null($where)) {
$select->where('id = ?', $where);
}
if (!is_null($order)) {
$select->order($order);
}
$rowset = $this->getGateway()->fetchAll($select);
$entities = array();
foreach ($rowset as $row) {
$entity = $this->createEntity($row);
$this->setMap($row->id, $entity);
$entities[] = $entity;
}
return $entities;
}
/**
* Abstract method to be implemented by concrete mappers.
*/
abstract protected function createEntity($row);
}
конкретная модель может выглядеть следующим образом:
<?php
class Application_Model_Mapper_Employee extends My_Model_Mapper_Abstract
{
protected $tableName = 'tab_employee';
//I hard code the $tableGateway though this is probably not the best way.
//$tableGateway should probably be injected, but I'm lazy.
public function __construct(Zend_Db_Table_Abstract $tableGateway = null)
{
if (is_null($tableGateway)) {
$tableGateway = new Application_Model_DbTable_User();
} else {
$tableGateway = $tableGateway;
}
parent::__construct($tableGateway);
}
//create the Entity model
protected function createEntity($row)
{
$data = array(
'id' => $row->id,
'name' => $row->name,
'password' => $row->password,
);
$employee = new Application_Model_Employee($data);
return $employee;
}
}
использовать это в контроллер может выглядеть следующим образом:
public function indexAction(){
model = new Application_Model_Mapper_Employee();
$employees = $model->findAll();
}
и самый прямой способ запроса база данных является наименее рекомендуемым способом, непосредственно от контроллера:
public function indexAction(){
model = new Application_Model_DbTable_Employee();
$employees = $model->fetchAll();
$this->view->employees = $employees
}
Надеюсь, это даст вам некоторую помощь, а не большую путаницу.
Может ли кто-нибудь помочь мне найти решение? – student