问题描述
我想使用PSR-0标准方式自动加载类,而无需添加包含,例如如何使用自动加载机制替换下面的代码:
I would like to use the PSR-0 Standard way to autoload classes without requiring to add includes, e.g. how can I replace the code below with the autoloading mechanism:
namespace Example;
use MyLib\Controller;
include_once './library/MyLib/Controller/AbstractController.php';
class MyController extends Controller\AbstractController {
[...]
因此,在上面的示例中,它表明在每个控制器中我都需要包含抽象控制器,这很疯狂……
So in the example above, it shows that in every controllers I need to include the abstract controller, which is crazy...
我在这里找到了PSR-0代码:
I have found the PSR-0 code here:
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
https://gist.github.com/221634
但是我不知道如何在我的应用程序中实现它.
But I have no idea how I need to implement this in my application.
推荐答案
您需要在应用程序的第一个脚本中包含(包括/要求语句)带有自动加载程序代码的文件
You need include (include/require statement) the file with the autoloader code in the first script of your application
如果按照@Skpd的说明选择使用Composer的自动加载器,则在第一个PHP脚本的顶部应该有这样的代码.
If you choose for use the Composer's autoloader as @Skpd said then you should have a code like this in the top of your first PHP script.
include_once __DIR__ . '/composer_autoloader.php'
$loader = new \Composer\Autoload\ClassLoader();
$loader->add('MyLib', __DIR__.'/library/');
$loader->register();
如果您决定使用Composer作为供应商经理,则将自定义名称空间添加到composer.json
并包含vendor/autoload.php
If you decide to use Composer as your vendor manager then add your custom namespaces to your composer.json
and include vendor/autoload.php
这篇关于PHP 5.3自动加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!