2011-04-11 22 views
1

我在libraries路徑上定義了一個插件,使用正確的目錄結構,並使其在application.ini文件中已知存在。該插件加載,並且我的preDispatch()方法觸發。但是,如何在實例化過程中將參數傳遞給插件?如何在實例化過程中將參數傳遞給我的Zend Framework插件?

這裏是我的代碼:

class Project_Controller_Plugin_InitDB extends Zend_Controller_Plugin_Abstract { 

    private $_config = null; 

    public function __contruct($config){ 
     $this->_config = $config; 
    } 

    public function preDispatch(Zend_Controller_Request_Abstract $request) { 
     $db = Zend_DB::factory("Pdo_Mysql", $this->_config); 
     Zend_Registry::set("db", $db); 
    } 

} 

具體來說,我如何通過$config__construct()方法?

感謝,

解決方案

這裏是我結束了(感謝菲爾·布朗!):

在我application.ini文件:

autoloaderNamespaces[] = "MyProjectName_" 

在我Bootstrap.php file:

protected function _initFrontControllerPlugins() { 
    $this->bootstrap('frontcontroller'); 
    $frontController = $this->getResource('frontcontroller'); 

    $plugin = new MyProjectName_Controller_Plugin_InitDB($this->_config->resources->db->params); 
    $frontController->registerPlugin($plugin); 
} 

回答

4

只需在您的Bootstrap類手動註冊您的插件

protected function _initFrontControllerPlugins() 
{ 
    $this->bootstrap('frontcontroller'); 
    $frontController = $this->getResource('frontcontroller'); 

    // Config could come from app config file 
    // or anywhere really 
    $config = $this->getOption('initDb'); 

    $plugin = new Project_Controller_Plugin_InitDB($config); 
    $frontController->registerPlugin($plugin); 
} 
+0

Right,AFAIK,如果你的插件需要參數,你不能通過'application.ini'實例化它。您需要在引導期間手動實例化,並在那裏傳遞參數,如上所述。 – 2011-04-11 01:13:43

+0

@David雖然我更喜歡我的答案中的方法,但您可以隨時將「bootstrap」invokeArg從插件中的前端控制器實例中提取出來,以便您訪問配置和資源。這依賴於FC的單身性質,儘管我總是嘗試和勸阻 – Phil 2011-04-11 01:17:37

+0

非常好!謝謝! – 2011-04-11 20:27:51

-1

你看過this嗎? $ Config結構非常類似於Zend_Config,所以如果你想傳遞額外的參數,把它作爲一個鍵/值的數組。

+0

我有存儲在我的'我application.ini'數據庫信息,所以我想我可以直接引用,在我插入。但是,如何將參數(如我所建議的)傳遞給沒有Zend_Config信息的其他插件? – 2011-04-11 00:34:27

相關問題