Php 如何在实例化期间将参数传递给Zend Framework插件?
我使用正确的目录结构在Php 如何在实例化期间将参数传递给Zend Framework插件?,php,zend-framework,Php,Zend Framework,我使用正确的目录结构在库路径上定义了一个插件,并在application.ini文件中公开了它的存在。插件加载,我的preDispatch()方法启动。但是,如何在实例化期间将参数传递给插件 这是我的密码: class Project_Controller_Plugin_InitDB extends Zend_Controller_Plugin_Abstract { private $_config = null; public function __contruct($co
库
路径上定义了一个插件,并在application.ini
文件中公开了它的存在。插件加载,我的preDispatch()
方法启动。但是,如何在实例化期间将参数传递给插件
这是我的密码:
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
传递给\u construct()
方法
谢谢
解决方案
以下是我的结局(感谢菲尔·布朗!)
在我的application.ini
文件中:
autoloaderNamespaces[] = "MyProjectName_"
protected function _initFrontControllerPlugins() {
$this->bootstrap('frontcontroller');
$frontController = $this->getResource('frontcontroller');
$plugin = new MyProjectName_Controller_Plugin_InitDB($this->_config->resources->db->params);
$frontController->registerPlugin($plugin);
}
在我的Bootstrap.php
文件中:
autoloaderNamespaces[] = "MyProjectName_"
protected function _initFrontControllerPlugins() {
$this->bootstrap('frontcontroller');
$frontController = $this->getResource('frontcontroller');
$plugin = new MyProjectName_Controller_Plugin_InitDB($this->_config->resources->db->params);
$frontController->registerPlugin($plugin);
}
你读过吗$配置结构与Zend_Config非常相似,因此如果您希望传递额外的参数,请将其视为键/值数组。只需在
引导类中手动注册插件即可
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);
}
使用我的数据库信息存储在我的应用程序.ini中,所以我想我可以在我的插件中直接引用它。但是,我怎样才能将参数(如我所建议的)传递给其他没有Zend_配置信息的插件呢?好吧,好吧,如果你的插件需要参数,你不能纯粹通过application.ini
实例化它。您需要在引导过程中手动实例化,并在那里传递参数,如上所述。@David虽然我更喜欢我回答中的方法,但您始终可以从插件中的front controller实例中拉出“bootstrap”invokeArg,这样您就可以访问配置和资源。这取决于FC的单亲性质,尽管我一直试图阻止它。布朗:绝对。如果插件需要配置中的参数,最好在实例化时实际传递它们,而不是让插件从singleton FC中提取它们。去自由贸易区