Laravel服务提供商不约束合同 [英] Laravel service provider not binding to contract
问题描述
我具有以下由服务提供商绑定的合同/接口,但是我得到以下错误:
i have below contract/interface which is binded by a service provider ,however the i get below error :
RouteDependencyResolverTrait.php第81行中的ReflectionException: 类App \ Http \ Controllers \ RocketShipContract不存在
ReflectionException in RouteDependencyResolverTrait.php line 81: Class App\Http\Controllers\RocketShipContract does not exist
我在做什么错了?
合同
namespace App\Contracts\Helpers;
Interface RocketShipContract
{
public function blastOff();
}
具体课程
namespace app\Contracts;
use App\Contracts\Helpers\RocketShipContract;
class RocketShip implements RocketShipContract
{
public function blastOff()
{
return 'Houston, we have ignition';
}
}
服务提供商
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Contracts\RocketShip;
class RocketShipServiceProvider extends ServiceProvider
{
protected $defer = true;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('App\Contracts\Helpers\RocketShipContract', function($app){
return new App\Contracts\RocketShip($app['HttpClient']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['App\Contracts\Helpers\RocketShipContract'];
}
}
控制器
public function test(RocketShipContract $rocketship)
{
$boom = $rocketship->blastOff();
return view('test.index', compact('boom'));
}
推荐答案
该错误提示您该问题:正在App\Http\Controllers
名称空间中解析该类.这是因为您需要在控制器中指定接口的完整名称空间.
The error you're getting hints at the problem: the class is being resolved in the App\Http\Controllers
namespace. That's because you need to specify the full namespace of your interface in the controller.
因此可以在use
语句中包含它:
So either include it with a use
statement:
use App\Contracts\Helpers\RocketShipContract;
或键入提示完整的名称空间:
Or type hint the full namespace:
public function test(App\Contracts\Helpers\RocketShipContract $rocketship)
{
// ...
}
这篇关于Laravel服务提供商不约束合同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!