Naguib Ihab
Naguib Ihab

Reputation: 4496

PSR4 - using autoload in composer instead of require

I am new with SLIM3 and followed a tutorial to install it while using Composer. In the tutorial I attempted to use autoload to load up all my classes without having to use require, here's my file structure:

dev
|── composer.json
|── index.php
|──── classes
|──── vendor

here's my composer.json file:

{
    "require": {
        "slim/slim": "^3.0",
        "monolog/monolog": "^1.23"
    },
    "autoload": {
        "psr-4": {
            "": "classes/"
        }
    }
}

and here's pdf.class.php which is sitting under classes

dev
|── composer.json
|── index.php
|──── classes
     |─ pdf.class.php
|──── vendor

class pdfClass {
    public function testme(){
        return 'i am working';
        $this->logger->addInfo("Something interesting happened");
    }
}

and the index.php:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

// Require for loading the vendor libraries installed by composer
require 'vendor/autoload.php';
// require 'classes/pdf.class.php'; // << If I uncomment this line it works.


$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;

$app = new \Slim\App(["settings" => $config]);
$container = $app->getContainer();

$app->post('/{controller}/{function}', function (Request $request, Response $response) {
    $headers = $request->getHeaders();
    $params = $request->getParsedBody();

    $classname = $request->getAttribute('controller').'Class';

    $controller = new $classname;
    $function = $request->getAttribute('function');

    $result = $controller->$function();

    $response->getBody()->write($result);
    return $response;
});

$app->run();

Shouldn't the autoload part in composer.json allow me to use the class without the need to require it?

Upvotes: 0

Views: 653

Answers (1)

Greg
Greg

Reputation: 6628

Not sure what is your exact problem is, but psr-4 requires the name of a file be exactly as the name of a class, so in your case probably Pdf.php not pdf.class.php:

The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.

http://www.php-fig.org/psr/psr-4/

Upvotes: 1

Related Questions