我正试图在laravel控制器中使用一个非laravel composer包。我已经将该项目添加到composer.json文件中,如下所示:
"require": {
"laravel/framework": "5.0.*",
"php": ">=5.4.0",
"abraham/twitteroauth": "0.5.2"
},
然后我跑了:
composer update
在项目中,它已经按预期将包安装在vendor/目录中,我在那里看到了它。但是,当向控制器添加以下代码时:
<?php
namespace App'Http'Controllers;
class HomeController extends Controller {
use Abraham'TwitterOAuth'TwitterOAuth;
public function index()
{
$o = new TwitterOauth();
return view('home');
}
Laravel返回以下错误:
未找到属性"App''Http''Controllers''Araham''TwitterOAuth''TwitterOAuth"
我怀疑这与名称空间已经声明有关,但我对PHP名称空间的了解不够,无法解决这个问题。
欢迎任何帮助!
您的控制器文件位于App'Http'Controllers
命名空间中
namespace App'Http'Controllers;
您试图使用相对类/特征名称向控制器添加特征
use Abraham'TwitterOAuth'TwitterOAuth;
如果您使用一个相对的trait名称,PHP会假设您希望trait在当前命名空间中,这就是它抱怨的原因
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"在这个名称空间中使用这个类,而不使用名称空间前缀"。如果从类中删除use
语句
class HomeController extends Controller {
//use Abraham'TwitterOAuth'TwitterOAuth;
}
并将其放置在namespace
关键字下的外部
namespace App'Http'Controllers;
use Abraham'TwitterOAuth'TwitterOAuth;
您应该能够使用类TwitterOAuth
来实例化您的对象。