我正在尝试在 Laravel Controller 中使用非 Laravel Composer 包。我已将项目添加到 composer.json 文件中,如下所示:
"require": {
"laravel/framework": "5.0.*",
"php": ">=5.4.0",
"abraham/twitteroauth": "0.5.2"
},
然后我跑了:
composer update
在项目中,它已按预期将包安装在 vendor/目录中,我在那里看到了它。但是,在 Controller 中添加以下代码时:
<?php
namespace App\Http\Controllers;
class HomeController extends Controller {
use Abraham\TwitterOAuth\TwitterOAuth;
public function index()
{
$o = new TwitterOauth();
return view('home');
}
Laravel 返回以下错误:
Trait 'App\Http\Controllers\Abraham\TwitterOAuth\TwitterOAuth' not found
我怀疑这与已经声明了命名空间这一事实有关,但我对 PHP 命名空间的了解还不足以解决这个问题。
欢迎任何帮助!
最佳答案
你的 Controller 文件在 App\Http\Controllers
命名空间中
namespace App\Http\Controllers;
您试图使用相对类/特征名称向您的 Controller 添加特征
use Abraham\TwitterOAuth\TwitterOAuth;
如果您使用相对特征名称,PHP 会假设您想要当前命名空间中的特征,这就是它提示的原因
App\Http\Controllers\Abraham\TwitterOAuth\TwitterOAuth
或
App\Http\Controllers\
combined with
Abraham\TwitterOAuth\TwitterOAuth
尝试使用绝对特征名称,你应该没问题
use \Abraham\TwitterOAuth\TwitterOAuth;
或者,将 TwitterOAuth
导入当前命名空间
namespace App\Http\Controllers;
use Abraham\TwitterOAuth\TwitterOAuth;
然后与短名称一起使用
class HomeController extends Controller {
use TwitterOAuth;
}
更新:
好吧,我们要责怪 PHP 对 use
的双重使用。在你的类定义中,你说
class HomeController extends Controller {
use Abraham\TwitterOAuth\TwitterOAuth;
public function index()
{
$o = new TwitterOauth();
return view('home');
}
}
当您在类中使用 use
时,PHP 会将其解释为“将此特性应用于此类”。我不熟悉这个库,所以我假设 Abraham\TwitterOAuth\TwitterOAuth
是一个特征。不是。
当您在类定义的 之外使用use
时,您是在告诉PHP“在没有 namespace 前缀的情况下在此 namespace 中使用此类”。如果您从类中删除 use
语句
class HomeController extends Controller {
//use Abraham\TwitterOAuth\TwitterOAuth;
}
并将它放在外面,namespace
关键字下
namespace App\Http\Controllers;
use Abraham\TwitterOAuth\TwitterOAuth;
您应该能够使用类 TwitterOAuth
来实例化您的对象。
关于php - Laravel 在 Controller 中使用非 Laravel Composer 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29154527/