我有一个模型,名为Admin with custom functions。
<?php
namespace ZendCustom\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Exception\ErrorException;
abstract class Admin {
/**
* @var TableGateway
*/
protected $_table;
/**
* @var array
*/
protected $data;
/**
* @var bool
*/
protected $loaded = false;
/**
* Constructor
*
* @param array $data
* @throws Exception
*/
public function __construct(array $data = array()) {
if (!is_null($this->_table)) {
if (!empty($data)) {
$this->loaded = !empty($this->data);
}
} else {
die('Please, specify table for ' . __CLASS__);
}
}
}
文档说要描述表,我们应该使用:
// module/Album/src/Album/Controller/AlbumController.php:
public function getAlbumTable()
{
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
http://framework.zend.com/manual/2.0/en/user-guide/database-and-models.html
如何在没有Controller的情况下在管理模型中设置我的模型表?
答案 0 :(得分:3)
您可以在通过服务管理器实例化时注入它。
Module.php
/**
* Get the service Config
*
* @return array
*/
public function getServiceConfig()
{
return array(
'factories' => array(
'ZendCustom\Model\AdminSubclass' => function($sm) {
// obviously you will need to extend your Admin class
// as it's abstract and cant be instantiated directly
$model= new \ZendCustom\Model\AdminSublcass();
$model->setAlbumTable($sm->get('Album\Model\AlbumTable'));
return $model;
},
)
)
}
admin.php的
abstract class Admin {
protected $_albumTable;
/**
* @param \Album\Model\AlbumTable
*/
public function setAlbumTable($ablum)
{
this->_albumTable = $ablum;
}
}
现在,如果你想要你的Admin类(或者它的一个sublcass而不是..)那么你使用Service Manage获取实例,它将注入你想要的表对象..
在控制器内你可以这样做:
$admin = $this->getServiceLocator()->get('ZendCustom\Model\AdminSubclass');