gpt4 book ai didi

php - Zend Framework 2 在模型中实例化表

转载 作者:搜寻专家 更新时间:2023-10-30 20:18:49 25 4
gpt4 key购买 nike

我有一个名为 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 $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 的情况下在管理模型中设置我的模型表?

最佳答案

您可以在通过服务管理器实例化时注入(inject)它。

模块.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;
},
)
)
}

管理.php

abstract class Admin {

protected $_albumTable;

/**
* @param \Album\Model\AlbumTable
*/
public function setAlbumTable($ablum)
{
this->_albumTable = $ablum;
}
}

现在,如果您想要您的 Admin 类(或者它的子类),那么您可以使用服务管理器来获取实例,它会注入(inject)您想要的表对象。

在 Controller 中你可以这样做:

$admin = $this->getServiceLocator()->get('ZendCustom\Model\AdminSubclass');

关于php - Zend Framework 2 在模型中实例化表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17336735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com