简体   繁体   中英

psr-4 autoloading not working in Laravel 4

I'm trying to create a directory to store custom classes, so I create the directory app/ArgumentClub/Transformers , and the class UserTransformer.php in that folder.

I then autoload with:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php"
    ],
    "psr-4": {
        "ArgumentClub\\": "app/ArgumentClub"
    }
},

And run composer dump-autoload . And namespace like this:

<?php namespace ArgumentClub\Transformers;

class UserTransformer {

I'm calling this class within another class like this:

<?php

use Sorskod\Larasponse\Larasponse;
use ArgumentClub\Transformers;

class UsersController extends \BaseController {

    ...

    $transformed = $this->fractal->collection($users, new UserTransformer());

But I get the error:

Class 'UserTransformer' not found

What am I doing wrong here?

You're not using the use correctly.

use ArgumentClub\\Transformers; imports that Namespace, but doesn't import the class you want to use.

To fix it you can either extend the use statement (which you should) to be like so:

use ArgumentClub\Transformers\UserTransformer

Or you can add the Transformers namespace to where you instantiate your UserTransformer class

$transformed = $this->fractal->collection($users, new Transformers\UserTransformer());

When you want to instantiate a namespaced class without putting the full namespace, you need to put the full class path in the use statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM