1

我正在开发自定义 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 。有任何想法吗?

4

1 回答 1

0

要从另一个组件访问$dbExternal变量,您需要先实例化一个MyController对象。在您拥有 的实例之前,该$dbExternal变量在任何地方都不存在MyController

$myController = new MyController();
$dbExternal = $myController->$dbExternal;
于 2012-12-13T23:51:17.013 回答