我看到您正在使用和作为类命名约定。controller_*****
model_*****
我读了一篇很棒的文章,它建议使用php的替代命名约定。namespace
我喜欢这个解决方案,因为我把课程放在哪里并不重要。无论它在我的文件结构中的哪个位置,都会找到它。它还允许我随心所欲地称呼我的类。我不需要类命名约定即可使我的代码正常工作。__autoload
例如,您可以设置文件夹结构,例如:
您的类可以按如下方式进行设置:
<?php
namespace application\controllers;
class Base {...}
和:
<?php
namespace application\models;
class Page {...}
自动加载机可能如下所示(或看到末尾的“自动加载说明”):
function __autoload($className) {
$file = $className . '.php';
if(file_exists($file)) {
require_once $file;
}
}
然后。。。您可以通过三种方式调用类:
$controller = new application\controllers\Base();
$model = new application\models\Page();
或
<?php
use application\controllers as Controller;
use application\models as Model;
...
$controller = new Controller\Base();
$model = new Model\Page();
或
<?php
use application\controllers\Base;
use application\models\Page;
...
$controller = new Base();
$model = new Page();
编辑 - 关于自动加载的说明:
我的主自动加载器看起来像这样:
// autoload classes based on a 1:1 mapping from namespace to directory structure.
spl_autoload_register(function ($className) {
# Usually I would just concatenate directly to $file variable below
# this is just for easy viewing on Stack Overflow)
$ds = DIRECTORY_SEPARATOR;
$dir = __DIR__;
// replace namespace separator with directory separator (prolly not required)
$className = str_replace('\\', $ds, $className);
// get full name of file containing the required class
$file = "{$dir}{$ds}{$className}.php";
// get file if it is readable
if (is_readable($file)) require_once $file;
});
这个自动加载器是类名到目录结构的直接1:1映射;命名空间是目录路径,类名是文件名。因此,上面定义的类将加载文件 。application\controllers\Base()
www/application/controllers/Base.php
我将自动加载程序放入一个文件,bootstrap.php,它位于我的根目录中。这可以直接包含,也可以修改php.ini以auto_prepend_file,以便它自动包含在每个请求中。
通过使用spl_autoload_register您可以注册多个自动装入函数,以便以所需的任何方式装入类文件。也就是说,您可以将部分或全部类放在一个目录中,也可以将部分或全部命名空间类放在一个文件中。非常灵活的:)