danyal14
danyal14

Reputation: 367

Slim3 PSR-4 autoloader

I am writing Slim3 API, for some reason slim is not loading namespace defined in composer.

Here is the project structure.

FolderStruc:

projectApi

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

My composer file packages and PSR-4 autoloader settings.

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 fails to load namespace \ProjectName\Api\Controllers\CategoryController

any idea where and what is going wrong?

Best Regards Danyal

Upvotes: 2

Views: 1813

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15696

You have incorrect autoloader definitions in your composer.json file.

The pattern is:

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

So in your case it probably should be:

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

autoload-dev definition is assuming there's a tests directory under project root path, which is not mentioned in your question.

Upvotes: 2

Related Questions