Php Zend Framework 2在模型中实例化表
我有一个模型,名为Admin,带有自定义函数Php Zend Framework 2在模型中实例化表,php,database,zend-framework2,Php,Database,Zend Framework2,我有一个模型,名为Admin,带有自定义函数 <?php namespace ZendCustom\Model; use Zend\Db\TableGateway\TableGateway; use Zend\Db\Exception\ErrorException; abstract class Admin { /** * @var TableGateway */ protected $_table; /** * @var array */ protected $dat
<?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.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;
}
}
现在,如果您想要管理类(或者它的子类,而不是..),那么您可以使用服务Manage来获取实例,它将注入您想要的表对象
在控制器内,您可以执行以下操作:
$admin = $this->getServiceLocator()->get('ZendCustom\Model\AdminSubclass');
谢谢,这就是工作!但是有几个模型呢。我应该为每一个创建注入吗?当然,或者您可以只通过服务定位器本身,这是您的选择:)
$admin = $this->getServiceLocator()->get('ZendCustom\Model\AdminSubclass');