为什么我的 Laravel 模块中出现“找不到类”错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25787376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting a "class not found" error in my Laravel module?
提问by Alankar More
I am using "laravel/framework": "4.2. *" version, and I want to use the module system for my project. I have followed the instructions provided in this document.
我使用的是 "laravel/framework": "4.2.*" 版本,我想在我的项目中使用模块系统。我已按照本文档中提供的说明进行操作。
I can create modules by using the command: php artisan modules:create module_name
. I have created an admin module in my app directory, and the module's directory structure has been created.
我可以使用以下命令创建模块:php artisan modules:create module_name
. 我在我的应用程序目录中创建了一个管理模块,并且模块的目录结构已经创建。
I am using DB::select('some SQL statement')
in one of the actions of the controller from the admin module, but it is giving me the following error:
我DB::select('some SQL statement')
在管理模块中的控制器操作之一中使用,但它给了我以下错误:
Class 'App\Modules\Admin\Controllers\DB' not found.
找不到类“App\Modules\Admin\Controllers\DB”。
Why is it not able to find this class?
为什么找不到这个类?
回答by David Barker
When using DB
or any other Laravel facades outside the root namespace, you need to make sure you actually use the class in the root namespace. You can put a \
before the class.
在DB
根命名空间之外使用或任何其他 Laravel 外观时,您需要确保您实际使用了根命名空间中的类。你可以\
在课前放一个。
\DB::select(...)
Or you can use the use
keyword in your class file to allow the use of a different namespaced class without explicitly writing out the namespace each time you use it.
或者您可以use
在类文件中使用关键字来允许使用不同的命名空间类,而无需在每次使用时明确写出命名空间。
<?php namespace App\Modules\Admin\Controllers;
use DB;
use BaseController;
class ModuleController extends BaseController {
public function index()
{
// This will now use the correct facade
$data = DB::select(...);
}
}
Note that the use
keyword always assumes it is loading a namespace from the root namespace. Therefore a fully qualified namespace is always required with use
.
请注意,该use
关键字始终假定它正在从根名称空间加载名称空间。因此,始终需要一个完全限定的命名空间use
。
回答by Ramesh
or else you can use autoload in composer.json
否则你可以在 composer.json 中使用自动加载
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
回答by Ruan Nawe
use Illuminate\Support\Facades\DB;
使用 Illuminate\Support\Facades\DB;