从不同文件夹自动加载类
这就是我自动加载 controllers
文件夹中所有类的方式,
# 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/
(但这不是重复的吗??)?
谢谢。
编辑:
这些是我在控制器文件夹中的类文件名:
class_controller_base.php
class_factory.php
etc
这些是我在模型文件夹中的类文件名:
class_model_page.php
class_model_parent.php
etc
这是我通常命名我的控制器类的方式(我使用下划线和小写字母),
class controller_base
{
...
}
class controller_factory
{
...
}
这是我通常命名模型类的方式(我使用下划线和小写字母),
class model_page
{
...
}
class model_parent
{
...
}
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);
}
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??)?
Thanks.
EDIT:
these are my classes file names in the controller folder:
class_controller_base.php
class_factory.php
etc
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
{
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
我看到您正在使用
controller_*****
和model_*****
作为类命名约定。我读了一篇很棒的 文章,建议使用 php 的
命名空间
进行替代命名约定。我喜欢这个解决方案,因为我把课程放在哪里并不重要。无论它位于我的文件结构中的哪个位置,
__autoload
都会找到它。它还允许我随意称呼我的课程。我的代码不需要类命名约定即可工作。例如,您可以设置文件夹结构,例如:
您的类可以像这样设置:
并且:
自动加载器可能看起来像这样(或参见最后的“自动加载注释”):
然后...您可以在中调用类三种方式:
或,
或,
编辑 - 关于自动加载的注释:
我的主要自动加载器如下所示:
此自动加载器是类名到目录结构的直接 1:1 映射;命名空间是目录路径,类名是文件名。因此,上面定义的类
application\controllers\Base()
将加载文件www/application/controllers/Base.php
。我将自动加载器放入文件 bootstrap.php 中,该文件位于我的根目录中。这可以直接包含,也可以将 php.ini 修改为 auto_prepend_file 以便它自动包含在每个请求中。
通过使用 spl_autoload_register 您可以注册多个自动加载函数以按照您想要的方式加载类文件。即,您可以将部分或全部类放在一个目录中,或者您可以将部分或全部 同一个文件中的命名空间类。非常灵活:)
I see you are using
controller_*****
andmodel_*****
as a class naming convention.I read a fantastic article, which suggests an alternative naming convention using php's
namespace
.I love this solution because it doesn't matter where I put my classes. The
__autoload
will find it no matter where it is in my file structure. It also allows me to call my classes whatever I want. I don't need a class naming convention for my code to work.You can, for example, set up your folder structure like:
Your classes can be set up like this:
and:
The autoloader could look like this (or see 'a note on autoloading' at the end):
Then... you can call classes in three ways:
or,
or,
EDIT - a note on autoloading:
My main auto loader looks like this:
This autoloader is a direct 1:1 mapping of class name to directory structure; the namespace is the directory path and the class name is the file name. So the class
application\controllers\Base()
defined above would load the filewww/application/controllers/Base.php
.I put the autoloader into a file, bootstrap.php, which is in my root directory. This can either be included directly, or php.ini can be modified to auto_prepend_file so that it is included automatically on every request.
By using spl_autoload_register you can register multiple autoload functions to load the class files any which way you want. Ie, you could put some or all of your classes in one directory, or you could put some or all of your namespaced classes in the one file. Very flexible :)
您应该命名您的类,以便将下划线 (
_
) 转换为目录分隔符 (/
)。一些 PHP 框架可以做到这一点,例如 Zend 和 Kohana。因此,您将类命名为
Model_Article
并将文件放入classes/model/article.php
中,然后自动加载...另请注意,您可以使用
spl_autoload_register()
使任何函数自动加载功能。它也更灵活,允许您定义多个自动加载类型函数。编辑
You should name your classes so the underscore (
_
) translates to the directory separator (/
). A few PHP frameworks do this, such as Zend and Kohana.So, you name your class
Model_Article
and place the file inclasses/model/article.php
and then your autoload does...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.Edit
我必须提到一些有关“良好”自动加载脚本和代码结构的内容,因此请仔细阅读以下内容
请记住:
,例如:Example.php 包含
例如:/Path1/Path2/Example.php 匹配
例如:/Path1/ Path2/Example.php 与 root:
考虑到这一点,我制作了以下脚本:
放在哪里..
记住:
快乐编码;-)
对其他答案进行一些回顾:
这只是我的个人意见 - 无意冒犯!
https://stackoverflow.com/a/5280353/ 626731
@alex 很好的解决方案,但不要让你的类名为错误的文件结构付出代价;-)
这是命名空间的工作
https://stackoverflow.com/a/5280510/626731 @Mark-Eirich 它有效,但是这样做的风格非常令人讨厌/丑陋/缓慢/僵硬[..]..
https://stackoverflow.com/a /5284095/626731 @tealou 要解决他的问题,这是迄今为止最明确的方法:-) ..
https ://stackoverflow.com/a/9628060/626731 @br3nt 这反映了我的观点,但是请(!)..不要使用 strtr! ..这让我到:
https://stackoverflow.com/a/11866307/626731 @Iscariot ..给你,一点“你知道的废话基准:
来源:http:// www.simplemachines.org/community/index.php?topic=175031.0
问题?..(但事实上他关于完整路径的说法是正确的)
https://stackoverflow.com/a/12548558/626731 @Sunil-Kartikey
https://stackoverflow.com/a/17286804/626731 @jurrien
永远不要在时间紧迫的环境中循环!不要在操作系统上搜索文件! - 慢
https://stackoverflow.com/a/21221590/626731 @sagits ..比 Marks 好得多;-)
I have to mention something about "good" autoload scripts and code structure, so read the following CAREFULLY
Keep in Mind:
e.g: Example.php contains
e.g: /Path1/Path2/Example.php matches
e.g: /Path1/Path2/Example.php with root:
With this in mind, i produced the following script:
Where to place it..
Remeber:
Happy coding ;-)
A little review at other answers:
THIS IS JUST MY PERSONAL OPINION - NO OFFENSE INTENDED!
https://stackoverflow.com/a/5280353/626731
@alex good solution, but don't make you class names pay for bad file structures ;-)
this is job for namespaces
https://stackoverflow.com/a/5280510/626731 @Mark-Eirich it works, but its pretty nasty/ugly/slow/stiff[..] style to do it this way..
https://stackoverflow.com/a/5284095/626731 @tealou for his problem to be solved this is the most clear approach so far :-) ..
https://stackoverflow.com/a/9628060/626731 @br3nt this reflects my point of view, but please(!) .. dont use strtr!! .. which brings me to:
https://stackoverflow.com/a/11866307/626731 @Iscariot .. to you, a little "you-know-bullshit-benchmark:
Source: http://www.simplemachines.org/community/index.php?topic=175031.0
Questions?.. (But he is in fact right about full path including)
https://stackoverflow.com/a/12548558/626731 @Sunil-Kartikey
https://stackoverflow.com/a/17286804/626731 @jurrien
NEVER loop in time critical environment! Don't search for files on os! - SLOW
https://stackoverflow.com/a/21221590/626731 @sagits .. much better than Marks ;-)
这是我的解决方案,
我不确定它是否是最好的解决方案,但它似乎工作得很好......
你觉得怎么样?
Here is my solution,
I'm not sure whether it is the best solution or not but it seems to work perfectly...
What do you think??
我的@Mark Eirich 答案版本:
在我的例子中,只有控制器类的名称中包含关键字,请根据您的需要进行调整。
My version of @Mark Eirich answer:
In my case only controller class have the keyword in their name, adapt it for your needs.
我可以给您最简单的答案,无需写下那些复杂的代码,甚至无需使用名称空间(如果这让您感到困惑)
示例代码。 100% 有效。
我想这个逻辑本身是可以解释的。干杯伙计!希望这有帮助:)
Simpliest answer I can give you without writing down those complex codes and even without using the namespace (if this confuses you)
Sample Code. Works 100%.
I guess the logic is explainable itself. Cheers mate! Hope this helps :)
这就是我要做的:
只要您的文件命名一致,例如
class_controller_*.php
和class_model_*.php
,这应该可以正常工作。Here's what I'd do:
As long you name your files consistently, like
class_controller_*.php
andclass_model_*.php
, this should work fine.每个人都在处理和粘贴从互联网上获得的代码中的内容(所选答案除外)。他们都使用字符串替换。
String Replace 比 strtr 慢 4 倍。你应该用它来代替。
在包含自动加载的类时,您还应该使用完整路径,因为操作系统解析路径所需的时间更少。
Everyone is is coping and pasting things from code they got off the internet (With the exception of the selected answer). They all use String Replace.
String Replace is 4 times slower than strtr. You should use it instead.
You should also use full paths when including classes with autoloading as it takes less time for the OS to resolve the path.
不应使用 __autoload() 函数,因为不鼓励这样做。请改用 spl_autoload()、spl_autoload_register()。 __autoload() 只能加载一个类,而 spl_autoload() 可以加载 1 个以上的类。更重要的是,将来 __autoload() 可能会被弃用。更多内容可以在 http://www.php.net/manual 上找到/en/function.spl-autoload.php
__autoload() function should not be use because it is not encourged. Use spl_autoload(), spl_autoload_register() instead. __autoload() just can load one class but spl_autoload() can get more than 1 classes. And one thing more, in future __autoload() may deprecated. More stuff can be find on http://www.php.net/manual/en/function.spl-autoload.php
尽管这个脚本没有名称约定,而且这个线程已经有点旧了,以防有人正在寻找可能的答案,这就是我所做的:
不确定它是否真的是最佳的,但它通过以下方式搜索文件夹递归读取dir。通过创造性的 str_replace 函数,您可以得到您的名字约定。
Altough this script doesn't have the name convention and this thread is already a bit old, in case someone is looking of a possible answer, this is what I did:
not sure if it is really optimal, but it searches through the folders by reading dir recursively. With a creative str_replace function you can get your name cenvention.
我用这个。基本上将文件夹结构(MVC 等)定义为序列化数组中的常量。然后在自动加载类中调用该数组。对我来说工作效率很高。
显然,您可以使用另一个函数创建文件夹数组,但对于 MVC,您也可以手动输入它。
为此,您需要调用您的类...... class.classname.php
I use this. Basically define your folder structure (MVC etc) as a constant in a serialised array. Then call the array in your autoload class. Works efficiently for me.
You could obviously create the folder array using another function but for MVC you may as well type it in manually.
For this to work you need to call your classes ...... class.classname.php