Search code examples
phpcomposer-phppsr-4

Namespacing not working, using composer psr-4


I am using slim framework, composer, and psr-4 autoload.

This is in composer:

"Shorty\\":"app/Shorty"

Note: I tried the above also with "Shorty\\":"app/Shorty/Models"

directorry structure: app/Shorty/Models/Trap.php

Inside Trap.php:

namespace Shorty\Models;

use Illuminate\Database\Eloquent\Model as Eloquent;

    class Trap{
    #code here
    }

In my route:

$users=Trap::leftJoin('users', function($join){

and I get: Class 'Trap' not found

What did I do wrong?


Solution

  • If the class name would have been correct, you wouldn't receive this error message:

    Class 'Trap' not found
    

    but this

    Class 'Shorty\Models\Trap' not found
    

    Not mentioning the fully qualified class name including it's namespace tells me that your code that is missing the class neither has a namespace statement, nor does an import with use, to import this "Trap" class.

    Or to be more precise:

    This code will complain about a missing "Trap" class.

    Trap::leftJoin();
    

    This code would complain about a missing "Shorty\Models\Trap" class.

    \Shorty\Models\Trap::leftJoin();
    

    As well as this one:

    use Shorty\Models\Trap;
    
    Trap::leftJoin();
    

    Or this one:

    namespace Shorty\Models;
    
    Trap::leftJoin();
    

    When PHP complains about a class not being present, it always displays the fully evaluated, final name of that class, after aliases, relative namespace indirections and stuff.