自动加载和PSR-0/PSR-4


Autoloading and PSR-0/PSR-4

我和许多其他人一样,似乎很难理解何时以及如何使用自动加载。我想我理解composer和PSR-0/PSR-4的概念,以及这需要的目录结构。但如果我使用自己的MVC框架构建自己的项目

  • 我现在应该把我所有的类文件都放在vendor文件夹中的src文件夹中吗
  • 然后我是否编辑composer自动加载文件
  • 还是我仍然保留原来的结构,只使用我自己的自动加载器?

    -project
        -app
            -core /Main.php
            -controllers /Controller.php
            -models /User.php
        /index.php
    

既然composer自带自动加载器,它将加载我可能想包含在我的项目中的所有依赖项,如果我不想把我的网站变成一个分布式项目,我甚至需要自己的名称空间吗?为什么我不坚持使用includes/requires?

最后,如果我真的使用像这样的闭包来采用名称空间

 function __autoload($class){
    require $class .'.php';
 });

我需要在所有加载类的页面中使用autoload.php文件吗?就像我使用过去的旧include/request一样。以上文件正确吗?我认为名称空间应该是

<?php
namespace app'core;  //for Main.php
namespace app'controllers; //for Controller.php
use app'controllers'Controller; //if I call the class

在主文件(可能是/var/www/dist/index.php)的开头,只包含Composer或您使用的任何自动加载器。

<?php
if ( file_exists( __DIR__.'/path/to/vendor/autoload.php' ) )
    require __DIR__.'/path/to/vendor/autoload.php';

然后,您可以通过使用use语句为文件中使用的类添加快捷方式

use MyNamespace'Controller'Index,
    MyNamespace'Service'FooService;
use Zend'Foo'Bar;
use Symfony'Baz'Biz;
use Etc'Etc'Etc;
// Refers to 'Zend'Foo'Bar
$bar = new Bar;

或者在实例化类时只使用完整路径

$bar = new 'Zend'Foo'Bar;

要添加自己的命名空间,只需将其添加到composer.json文件中即可

"autoload" : {
    "psr-4" : {
        "MyNamespace''" : "src/"
    }
}

打开您的命令行界面/终端/控制台,并将名称空间添加到自动加载器

# local install of Composer in your project
php composer.php dump-autoload
# or global install and `composer` is in your $PATH
composer dump-autoload

有一条规则:

每个文件一类

如果您的项目确实与(PSR-0已弃用或)PSR-4兼容,那么在一个文件中不会使用多个namespace。类名(在PSR-4 FIG标准中)被定义为

完全限定类名具有以下形式:

'<NamespaceName>('<SubNamespaceNames>)*'<ClassName>

在";名称空间前缀";[注意:'是"根")对应于"基本目录"内的子目录,其中名称空间分隔符表示目录分隔符

以下示例:

+------------------------------+------------------+------------------------+---------------------------------------+
| Fully Qualified Class Name   | Namespace Prefix | Base Directory         | Resulting File Path                   |
+------------------------------+------------------+------------------------+---------------------------------------+
| 'Acme'Log'Writer'File_Writer | Acme'Log'Writer  | ./acme-log-writer/lib/ | ./acme-log-writer/lib/File_Writer.php |
+------------------------------+------------------+------------------------+---------------------------------------+