简体   繁体   中英

Laravel Namespace, how does it work?

I am new to Laravel 5 and I would like someone to explain to me how exactly Laravel's namespacing works.

So I had a class named Variant in app/models/Variant.php my code looks like this

namespace App;
use Illuminate\Database\Eloquent\Model;
class Variant extends Model{
  /*Some code*/
}

in my route.php I have:

use App\Variant;
/*calls Variant::all() some where in code*/

Then I get an error saying Variant is not defined. However, if I change my namespace in Variant.php from namespace App to namespace App\\Models and in route.php from use App\\Variant to use App\\Models\\Variant everything magically works.

Why is that? Does it have to do with php namespace or the classmap property in composer.json? I am very confused.

Your classes are probably loaded by composer. What's the content of it - autoloading section in particular?

I guess it's loaded by PSR-4 standard, which respects director-name\\file-name pattern.

Meaning:

  • App\\Variant is sought in app/Variant.php
  • App\\Models\\Variant is sought in app/models/Variant.php

Therefore, when you change your namespace to the one corresponding with your directory path, it works.

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