高效的自动加载功能
我目前正在构建自己的 PHP 框架,并创建了很多目录来存储我的类。
这是我当前的自动加载功能:
function __autoload($className)
{
$locations = array('', 'classes/', 'classes/calendar/', 'classes/exceptions/', 'classes/forms/', 'classes/table/', 'classes/user', 'pages/', 'templates/');
$fileName = $className . '.php';
foreach($locations AS $currentLocation)
{
if(file_exists($currentLocation . $fileName))
{
include_once ($currentLocation . $fileName);
return;
}
}
}
现在在我的主类文件中,我确实已经包含了所有必需的类,因此它们不会必须寻找。
我的问题是:
- 这个功能足够高效吗?是否会需要很长的加载时间,或者有什么办法可以最大限度地减少加载时间?
- include_once() 是我应该包含类的方式吗?
- 有没有一种方法可以让我编写函数来猜测最流行的文件夹?或者这会占用太多时间和/或不可能吗?
- 命名空间对我有帮助吗? (我现在正在阅读和学习它们。)
I currently am building my own PHP framework and am creating a lot of directories to store my classes in.
This is my current autoload function:
function __autoload($className)
{
$locations = array('', 'classes/', 'classes/calendar/', 'classes/exceptions/', 'classes/forms/', 'classes/table/', 'classes/user', 'pages/', 'templates/');
$fileName = $className . '.php';
foreach($locations AS $currentLocation)
{
if(file_exists($currentLocation . $fileName))
{
include_once ($currentLocation . $fileName);
return;
}
}
}
Now in my main class file I do have all of the necessary classes already included so that they won't have to be searched for.
Here are my questions:
- Is this function efficient enough? Will there be a lot of load time or is there a way for me to minimize the load time?
- Is include_once() the way that I should go about including the classes?
- Is there a way that I could write the function to guess at the most popular folders? Or would that take up too much time and/or not possible?
- Would namespaces help me at all? (I am reading and learning about them right now.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
require
,因为有两个原因:a) 如果文件已经包含,则不需要 PHP 跟踪,因为如果包含,则不需要首先调用 __autoload;b) 如果无法包含文件,无论如何您都无法继续执行作为参考,
__autoload
和名称空间之间的交互已记录在案< a href="http://us.php.net/manual/en/language.namespaces.rules.php" rel="nofollow noreferrer">此处。require
, for two reasons: a) you don't need to have PHP track if the file has been already included, because if it has it won't need to call__autoload
in the first place and b) if the file cannot be included you won't be able to continue execution anywayFor reference, the interaction between
__autoload
and namespaces is documented here.