如何调整自动加载器以便加载我的类?

时间:2017-07-04 11:44:19

标签: php namespaces autoload

我的项目结构如下:

init.php

我的脚本<?php use Bookstore\Domain\Book; use Bookstore\Domain\Customer; function autoloader($classname) { $lastSlash = strpos($classname, '\\') + 1; $classname = substr($classname, $lastSlash); $directory = str_replace('\\', '/', $classname); $filename = __DIR__ . '/src/' . $directory . '.php'; require_once($filename); } spl_autoload_register('autoloader'); $basic = new Basic(1, "name", "surname", "email"); $premium = new Premium(2, "name", "surname", "email"); var_dump($basic); var_dump($premium); 包含以下内容:

(...)
"autoload": {
    "psr-4": {
        "AppBundle\\": "src/AppBundle",
        "CoreBundle\\": "src/CoreBundle"
    },
(...)

我的错误是:

  

PHP警告:require_once(/srv/http/libro_php7/src/asic.php):无法打开流:第11行/srv/http/libro_php7/init.php中没有此类文件或目录   PHP致命错误:require_once():无法打开所需&#39; /srv/http/libro_php7/src/asic.php'第11行/srv/http/libro_php7/init.php中的(include_path =&#39;。:&#39;)

谢谢!

1 个答案:

答案 0 :(得分:0)

自动装

首先,您应该调整自动加载器以忽略不在Bookstore命名空间内的类名,并将其简化为:

function autoloader($classname) {
    /**
     * only handle classnames starting with "Bookstore\"
     */
    if (0 === strpos($className, 'Bookstore\\')) {
        $filename = __DIR__ . '/src/' . str_replace('\\', '/', $className) . '.php';

        require_once $filename;
    }
}

进口

其次,您缺少导入(这就是自动加载器无法正确找到您的类的原因

  • Bookstore\Domain\Customer\Basic
  • Bookstore\Domain\Customer\Premium(事件没有这么做,在创建实例之前就失败了)

调整导入

<?php

use Bookstore\Domain\Book;
use Bookstore\Domain\Customer\Basic;
use Bookstore\Domain\Customer\Premium;

// see definition above
spl_autoload_register('autoloader');

$basic = new Basic(1, "name", "surname", "email");
$premium = new Premium(2, "name", "surname", "email");
var_dump($basic);
var_dump($premium);

与进口相关的参考类

<?php

use Bookstore\Domain\Book;
use Bookstore\Domain\Customer;

// see definition above
spl_autoload_register('autoloader');

$basic = new Customer\Basic(1, "name", "surname", "email");
$premium = new Customer\Premium(2, "name", "surname", "email");
var_dump($basic);
var_dump($premium);