2016-01-05 56 views
0

我從Zend框架1.4至2.4遷移的項目,我有一類「供應商/自定義/班/ user.php的」Zend框架2 Access數據庫從定製庫

<?php 

namespace Classes; 

use Zend\Db\TableGateway\TableGateway; 
use Zend\ServiceManager\FactoryInterface; 
use Zend\ServiceManager\ServiceLocatorInterface; 
use Zend\Db\Adapter\Adapter; 

class User 
{ 
    public function getItemById($id) 
    { 
     //$config = $this->getServiceLocator()->get('config'); 
     //This only work in controller 
     $configs = array(); 
     $adapter = new Adapter($configs); 


     $projectTable = new TableGateway('project', $adapter); 
     $rowset = $projectTable->select(array('type' => 'PHP')); 

     echo 'Projects of type PHP: '; 
     foreach ($rowset as $projectRow) { 
      echo $projectRow['name'] . PHP_EOL; 
     } 
    } 
} 

?> 

我需要加載在我的文件「config/autoload」,global.php和local.php中合併配置。 $config = $this->getServiceLocator()->get('config');有人可以指導我如何從自定義類中獲取這些配置。基本上我試圖做的是編寫一組類,如用戶,項目,模型以外的客戶,並通常在所有模塊,如CMS,管理面板,網站中使用它們。感謝您的指導。

回答

0

由於沒有訪問這些配置沒有直接的方法的依賴關係。我已經在config/autoload的本地和全局php文件中使用DB訪問信息編寫了常量,並在我的課程中使用了它。

class DBManager 
{ 
    protected $adapter ; 
    protected $connection ; 

    /** 
    * Constructor 
    */ 
    public function __construct() 
    { 
     $configs = array(
      'hostname' => DB_SERVER_NAME, 
      'driver' => 'Pdo_Mysql', 
      'database' => DB_DATABASE_NAME, 
      'username' => DB_USER_NAME, 
      'password' => DB_PASSWORD , 
     ); 

     $this->adapter = new Adapter($configs); 
    } 

} 
0

方式可能是利用工廠。

你創建一個類UserFactory implementing Zend\ServiceManager\FactoryInterface。這個類將有一個方法createService$serviceLocator參數。您可以使用此服務定位器來檢索您的依賴項並將它們傳遞到User類。

在你User類,你需要使用接受的控制器參數,你需要傳遞給它