如何在 Laravel 5 中添加外部类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28816707/
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
How can I add external class in Laravel 5
提问by Hamed Kamrava
There is a class in app/Libraries/TestClass.php
with following content:
有一堂课,app/Libraries/TestClass.php
内容如下:
class TestClass {
public function getInfo() {
return 'test';
}
}
Now, I would like to call getInfo()
method from this external class in my Controller.
现在,我想getInfo()
从我的控制器中的这个外部类调用方法。
How can I do such thing?
我怎么能做这样的事情?
回答by lukasgeiter
First you should make sure that this class is in the right namespace. The correct namespace here would be:
首先,您应该确保此类位于正确的命名空间中。这里正确的命名空间是:
namespace App\Libraries;
class TestClass {
Then you can just use it like any other class:
然后你可以像其他任何类一样使用它:
$test = new TestClass();
echo $test->getInfo();
Don't forget the import at the top of the class you want to use it in:
不要忘记在您要在其中使用它的类顶部的导入:
use App\Libraries\TestClass;
In case you don't have control over the namespace or don't want to change it, add an entry to classmap
in your composer.json
:
如果您无法控制命名空间或不想更改它,请classmap
在您的composer.json
:
"autoload": {
"classmap": [
"app/Libraries"
]
}
Then run composer dump-autoload
. After that you'll be able to use it the same way as above except with a different (or no) namespace.
然后运行composer dump-autoload
。之后,您将能够以与上述相同的方式使用它,但使用不同的(或没有)命名空间。