我的应用程序有一个配置文件,但是我无法传递对象,因为我需要它可用于我的主索引页面和父控制器。
目前我必须在每个控制器中将它作为__Construct函数的参数传递,这当然不是最好的方法。
的index.php
<?PHP
require 'config/conf.php';
$errors = array();
//Memcache the config file at some point.
define('DEBUG_MODE', 0);
define('SITE_KEY', '');
define('ROOT', 'http://manager.com/');
define('Vs', 'views/');
define('Cs', 'controllers/');
function __autoload($className) { // Autoload both controllers and models.
if (stristr($className, 'Model')) {
if (is_readable(Ms . $className . '.php')) {
include Ms . $className . '.php';
}
} else {
if (is_readable(Cs . $className . '.php')) {
include Cs . $className . '.php';
}
}
}
require 'libs/core/Controller.php';
require 'libs/core/View.php';
$Memcache = null;
if ($config['ADDITIONAL_LIBS']['MEMCACHED']) {
if (!class_exists('Memcache')) {
$errors[] = array('code' => 1, 'type' => 'error', 'title' => 'Memcached failed to load', 'msg' => 'Memcached is not installed or initialised properly.');
}
}
if ($config['SESSIONS']) {
require 'libs/core/Session.php';
}
if ($config['DATABASE']) {
define('Ms', 'models/');
require 'libs/core/Database.php';
require 'libs/core/Model.php';
}
if ($config['ADDITIONAL_LIBS']['UTIL']) {
if (file_exists('libs/extra/Util.php')) {
require 'libs/extra/Util.php';
} else {
$errors[] = loadFail('Util');
}
}
if ($config['ADDITIONAL_LIBS']['PBKDF2']) {
if (file_exists('libs/extra/PBKDF2.php')) {
require 'libs/extra/PBKDF2.php';
} else {
$errors[] = loadFail('PBKDF2');
}
}
if ($config['ADDITIONAL_LIBS']['MCAPI']) {
if (file_exists('libs/extra/MCAPI.php')) {
require 'libs/extra/MCAPI.php';
} else {
$errors[] = loadFail('MCAPI');
}
}
require 'libs/core/Router.php';
$Site = new Router($Config, $errors);
function loadFail($moduleName) {
return array('code' => 1, 'type' => 'error', 'title' => $moduleName . ' failed to load', 'msg' => $moduleName . '.php was not found in the "libs/extra/" directory.');
}
我的conf文件:
$Config = new Config();
$Config->set('HOME_PAGE', 'index');
$Config->set('MEMCACHE_ENABLE', true);
$Config->set('MEMCACHE_SERVERS', array(
array(
'SERVER' => 'localhost',
'PORT' => '11211'
)
));
class Config {
public $params;
function __construct() {
}
public function set($param, $value) {
$this->params[$param] = $value;
}
public function get($param) {
return $this->params[$param];
}
}
我的主控制器类,我需要配置对象可以访问:
abstract class Controller {
public $view;
public $Memcache;
public function __construct($Config) {
// Autoload model if it exists...
$model = get_class($this) . 'Model';
if (is_readable(Ms . $model . '.php')) {
if ($Memcache) {
if (!$this->model = $Memcache->get($model)) {
$this->model = new $model;
}
}
}
$this->view = new View();
}
}
什么是实现我想要的光滑和干净的方式,基本上是有一个集中配置文件谁的参数可用于我的主索引文件和父控制器?
答案 0 :(得分:-2)
通常使用注册表模式处理配置: http://avedo.net/101/the-registry-pattern-and-php/
这可能是最常见/最直接的方式。有些人不喜欢使配置非常全局,在这种情况下,你经常使用Factory模式并让工厂注入配置,这样你就不必为每个实例化明确地执行它。