Slim3 PSR-4自动加载器

时间:2017-07-10 10:31:58

标签: php psr-4 slim-3

我正在编写Slim3 API,因为某些原因,slim没有加载在composer中定义的命名空间。

这是项目结构。

FolderStruc:

projectApi

 - composer.json
 - src
    - public
      - index.php
    - ProjectName
      - Api
        - Controllers
        - Entities
        - Commands

我的作曲家文件包和PSR-4自动加载器设置。

composer.json

{
    "require": {
        "slim/slim": "^3.0",
        "symfony/yaml": "3.1",
        "symfony/console": "3.1",
        "symfony/process": "3.1",
        "doctrine/orm": "^2.5",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/doctrine-cache-bundle": "^1.2",
        "sabre/xml": "1.1.0",
        "php-di/php-di": "@dev",
        "php-amqplib/php-amqplib": "@dev",
        "ramsey/uuid": "dev-master",
        "monolog/monolog": "~1.15@dev",
        "predis/predis": "~1.0.1",
        "spipu/html2pdf": "^4.5",
        "iio/libmergepdf": "~3.0"
    },
    "minimum-stability": "dev",
    "autoload": {
        "psr-4": {
            "src\\ProjectName\\": "src/ProjectName/"
        }
    },
    "autoload-dev": {
        "psr-4": { "src\\ProjectName\\Tests\\": "tests" }
    }
}

的index.php

CategoryController

namespace ProjectName\Api\Controllers;

class CategoryController
{

    /**
     * @param \Slim\App $app
     * @return array
     */
    public function index(\Slim\App $app)
    {
        return ['Cats', 'Cats2', 'Cats3'];
    }
}

** routes.php **

$app->get('/v1/category/list', function (Request $request, Response $response) {
    $response = $response->withHeader('Content-type', 'application/json');
    $categoryCtrl = new \ProjectName\Api\Controllers\CategoryController();
});

Slim无法加载namespace \ ProjectName \ Api \ Controllers \ CategoryController

任何想法在哪里以及出了什么问题?

最诚挚的问候 Danyal

1 个答案:

答案 0 :(得分:2)

您的composer.json文件中的自动加载器定义不正确。

模式是:

"psr-4": {
    "Namespace\\Prefix\\": "/path/to/source/root"
}

所以在你的情况下,它应该是:

"autoload": {
    "psr-4": {
        "ProjectName\\": "src/ProjectName/"
    }
},
"autoload-dev": {
    "psr-4": { "ProjectName\\Tests\\": "tests/" }
}

autoload-dev定义假设在项目根路径下有一个tests目录,在您的问题中没有提到。