0

I previously had a pretty simple autoload script working nicely, but as I've noticed that Doctrine2 is using Composer for this, I thought it might be nice to streamline everything. Unfortunately, Composer does not seem to be working as I understood it to.

Here is the relevant part of my composer.json

"autoload": {
    "psr-0": {
       "": "models/",
       "Catalog2\\Config": "class/"
    }
}

Note that the "": "models/" line used by Doctrine2 has been working just fine. After I ran composer update , the bottom part of my vendor/composer/autoload_namespaces.php looks like so:

'Doctrine\\Common\\' => array($vendorDir . '/doctrine/common/lib'),
'Catalog2\\Config' => array($baseDir . '/class'),
'' => array($baseDir . '/models'),

So far so good, I think. In my routes.php file (basically a front-controller) I have the following:

<?php
use Catalog2\Config;

//autoload classes
require_once __DIR__.'/vendor/autoload.php';

try {
    $router = new Router;
} catch(Exception $e ) {
    echo "<strong>Can't create router object</strong><br/>";
}

Here Catalog2\Config\Router should be calling my class/Router.php, which begins as follows:

<?php
namespace Catalog2\Config;

class Router {
    protected $resource; //what are we manipulating? A product? An order?
    protected $action; //what are we doing with that resource?

When I go to the page I get this:

Fatal error: Class 'Router' not found in /home/tom/Code/productCatalog2/routes.php on line 14

What is going wrong here? I repeat that Doctrine2 was able to autoload my model code from /models, so why aren't my changes working?

1 Answer 1

2

According to PSR-0 the namespace prefix will be included to the path.

So the complete filename for your class must be:

class/Catalog2/Config/Router.php

Meanwhile PSR-4 would behave like you expected: it will just match the namespace prefix and will not append it additionally to the given path.

References:

PS: you probably want the namespace prefix to be "Catalog2\\Config\\" (see the trailing slash)

Sign up to request clarification or add additional context in comments.

2 Comments

You're a lifesaver. I noticed that when I tried to use psr-4 in composer.json it generated a separate autoloader for the psr-4 paths. Is it possible/best practice to use both standards in the same application?
It is possible, just define both of them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.