我正在开发定制的Joomla 2.5后端组件。我想知道在我的组件范围内创建变量全局的最佳实践。我应该在组件主控制器中放置声明吗?
class MyController extends JController
{
/**
*
* @var object External database object
*/
public $dbExternal;
function __construct($config = array())
{
$this->dbExternal = $this->_getDbInstance();
JTable::setDbo($this->dbExternal);
parent::__construct($config);
}
/**
* Display task
*
* @return void
*/
function display($cachable = false, $urlparams = false)
{
// set default view if not set
JRequest::setVar('view', JRequest::getCmd('view', 'My'));
// call parent behavior
parent::display($cachable);
// Set the submenu
MyHelper::addSubmenu('messages');
}
/**
* Getting instance of the database
*
* @return instance $dbExternal Return db instance on success
*/
private function _getDbInstance()
{
$params = $this->_getDbParams();
$dbExternal = JDatabase::getInstance($params);
if ($dbExternal->getErrorNum() > 0)
{
JError::raiseWarning(500, 'JDatabase::getInstance: '.
$dbExternal->getErrorMsg());
$this->isError = true;
}
return $dbExternal;
}
/**
* Getting external db parameters
*
* @return array $dbParamsArr Return db params on success
*/
private function _getDbParams()
{
$dbParamsArr = array();
$params = JComponentHelper::getParams('com_my');
$dbParamsArr['host'] = $params->get('db_host');
$dbParamsArr['user'] = $params->get('db_user');
$dbParamsArr['password'] = $params->get('db_password');
$dbParamsArr['database'] = $params->get('db_database');
$dbParamsArr['driver'] = $params->get('db_driver');
return $dbParamsArr;
}
}
所以我想在任何其他组件控制器或模型中达到$ dbExternal。有什么想法吗?
答案 0 :(得分:0)
要从另一个组件访问$dbExternal
变量,您需要首先实例化MyController
对象。在您拥有$dbExternal
的实例之前,MyController
变量不存在于任何位置。
$myController = new MyController();
$dbExternal = $myController->$dbExternal;