2013-06-27 25 views
2

我有一個模型,名爲Admin with custom functions。Zend Framework 2實例化模型中的表格

<?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

我怎麼可以設置管理員模式在我的表型,無需控制器?

回答

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的

​​

現在,如果你希望你的管理類(或它而是一個sublcass ..)然後你使用服務管理得到實例,它會注入你想要的表格對象。

在控制器內部,你可以這樣做:

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

謝謝,這是工作!但是幾個模型呢。我應該爲它們每個創建注射嗎? – ShiftedReality

+0

當然,或者你可以通過服務定位器本身,這是你的選擇:) – Andrew