【发布时间】:2012-07-25 02:55:40
【问题描述】:
我正在 PHP 中创建一个基本的 MVC 结构化 CMS,作为了解 MVC 工作原理的一种方式(因此我没有使用真正的预构建引擎)。我有一个基本版本,目前正在尝试将信息转移到配置文件中,如下所示:
config.php
<?php
return array(
// MySQL database details
'database' => array(
'host' => 'localhost',
'port' => '',
'username' => '',
'password' => '',
'name' => '',
'collation' => 'utf8_bin'
),
// Application settings
'application' => array(
// url paths
'default_controller' => 'index',
'default_action' => 'index',
'timezone' => 'UTC',
),
// Session details
'session' => array(
'name' => '',
'expire' => 3600,
'path' => '/',
'domain' => ''
),
// Error handling
'error' => array(
'ignore' => array(E_NOTICE, E_USER_NOTICE, E_DEPRECATED, E_USER_DEPRECATED),
'detail' => false,
'log' => false
)
);
我将它包含在 index.php 文件中,如下所示:
index.php
define ('__SITE_PATH', $site_path);
$config = include __SITE_PATH . '/config.php';
但是,当我稍后尝试将其加载到模板文件中进行测试时,或者与此相关的任何其他文件中,什么都不会返回。这是课程的问题吗?如果有人能对此事有所了解,我将不胜感激。
这里是完整的 index.php 以供参考:
<?php
/*** error reporting on ***/
error_reporting(E_ALL);
/*** define the site path ***/
$site_path = realpath(dirname(__FILE__));
define ('__SITE_PATH', $site_path);
$config = include __SITE_PATH . '/config.php';
/*** include the controller class ***/
include __SITE_PATH . '/application/' . 'controller_base.class.php';
/*** include the registry class ***/
include __SITE_PATH . '/application/' . 'registry.class.php';
/*** include the router class ***/
include __SITE_PATH . '/application/' . 'router.class.php';
/*** include the template class ***/
include __SITE_PATH . '/application/' . 'template.class.php';
/*** auto load model classes ***/
function __autoload($class_name) {
$filename = strtolower($class_name) . '.class.php';
$file = __SITE_PATH . '/model/' . $filename;
if (file_exists($file) == false) {
return false;
}
include ($file);
}
/*** a new registry object ***/
$registry = new registry;
/*** load the router ***/
$registry->router = new router($registry);
/*** set the controller path ***/
$registry->router->setPath (__SITE_PATH . '/controller');
/*** load up the template ***/
$registry->template = new template($registry);
/*** load the controller ***/
$registry->router->loader();
【问题讨论】:
-
代码对我来说很合适。您是否尝试打印路径以确保包含正确的文件?
-
是的。现在做了两次。
-
如果你
include full/path/to/config.php然后var_dump($config);你什么都得不到?我刚刚在我的机器上做了一个简单的测试,它对我有用。 -
它会加载一些文件,例如它被调用的文件,然后说“router.class.php”。但是,当我尝试在路由器/模板类调用的文件中执行 var_dump 时,它根本不会加载,就好像根本没有 $config 一样
-
你应该只有 一个
include声明,那就是包括一个自动加载器,就像 composer 生成的一样。此外,我们不再执行“class.php”,您需要查看 PSR-0 / PSR-4 以及类的名称应该如何成为文件的名称,以便它可以自动加载而您不需要不需要输入“include”来获取它。
标签: php oop model-view-controller