从不同文件夹自动加载类 [英] Autoload classes from different folders
问题描述
这是我自动加载controllers
文件夹中的所有类的方式,
This is how I autoload all the classes in my controllers
folder,
# auto load controller classes
function __autoload($class_name)
{
$filename = 'class_'.strtolower($class_name).'.php';
$file = AP_SITE.'controllers/'.$filename;
if (file_exists($file) == false)
{
return false;
}
include ($file);
}
但是我在models
文件夹中也有类,我也想自动加载它们-我该怎么办?我应该复制上面的自动加载并仅将路径更改为models/
(但不是重复吗?)?
But I have classes in models
folder as well and I want to autoload them too - what should I do? Should I duplicate the autoload above and just change the path to models/
(but isn't this repetitive??)?
谢谢.
这些是控制器文件夹中我的班级文件名:
these are my classes file names in the controller folder:
class_controller_base.php
class_factory.php
etc
这些是我在class文件夹中的class文件名:
these are my classes file names in the model folder:
class_model_page.php
class_model_parent.php
etc
这通常是我命名控制器类类的方式(我使用下划线和小写),
this is how I name my controller classes class usually (I use underscores and lowcaps),
class controller_base
{
...
}
class controller_factory
{
...
}
这通常是我为模型类类命名的方式(我使用下划线和小写),
this is how I name my model classes class usually (I use underscores and lowcaps),
class model_page
{
...
}
class model_parent
{
...
}
推荐答案
您应命名您的类,以便将下划线(_
)转换为目录分隔符(/
).一些PHP框架可以做到这一点,例如Zend和Kohana.
You should name your classes so the underscore (_
) translates to the directory separator (/
). A few PHP frameworks do this, such as Zend and Kohana.
因此,您将类命名为Model_Article
并将文件放置在classes/model/article.php
中,然后自动加载就可以了...
So, you name your class Model_Article
and place the file in classes/model/article.php
and then your autoload does...
function __autoload($class_name)
{
$filename = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class_name)).'.php';
$file = AP_SITE.$filename;
if ( ! file_exists($file))
{
return FALSE;
}
include $file;
}
还请注意,您可以使用 spl_autoload_register()
来使任何功能成为自动加载功能.它还更加灵活,允许您定义多个自动加载类型的函数.
Also note you can use spl_autoload_register()
to make any function an autoloading function. It is also more flexible, allowing you to define multiple autoload type functions.
如果必须有多个自动加载功能,则spl_autoload_register()允许这样做.它有效地创建了自动加载功能队列,并按照定义的顺序遍历每个功能.相比之下,__autoload()只能定义一次.
If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.
修改
注意::自PHP 7.2.0起, __ autoload 已被弃用.强烈建议不要使用此功能.有关更多详细信息,请参考PHP文档. http://php.net/manual/zh/function.autoload.php
Note : __autoload has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged. Please refer to PHP documentation for more details. http://php.net/manual/en/function.autoload.php
这篇关于从不同文件夹自动加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!