当绑定由 Laravel 中的提供者完成时,使用 App::make 的依赖项解析不起作用
Dependency resolving with App::make not working when bind is done by a provider in Laravel
我正在使用 Laravel 5.2。我尝试如下解决 IOCContainer 中 Laravel 中的依赖项。(使用 App::make
方法)
App/FooController.php:-
<?php
namespace App\Http\Controllers;
use App\Bind\FooInterface;
use Illuminate\Support\Facades\App;
class FooController extends Controller
{
public function outOfContainer(){
dd(App::make('\App\bind\FooInterface')); // Focus: program dies here!!
}
}
在 AppServiceProvider 中完成的 FooInterface 绑定如下
App/Providers/AppServiceProvider.php:-
<?php
namespace App\Providers;
use App\Bind\Foo;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('\App\Bind\FooInterface', function() {
return new Foo();
});
}
}
Foo 的结构class 如下。
App/Bind/Foo.php:-
<?php
namespace App\Bind;
class Foo implements FooInterface {
}
FooInterface
接口结构如下:-
<?php
namespace App\Bind;
interface FooInterface {
}
然后我创建了如下路由
Route::get('/outofcontainer', 'FooController@outOfContainer');
但是当我导航到这条路线时,它会抛出错误文本异常:
BindingResolutionException in Container.php line 748:
Target [App\bind\FooInterface] is not instantiable.
这是怎么回事?
如何将 App:make() 与 AppServiceProvider 一起使用?
在您的服务提供商中,您正在绑定字符串 '\App\Bind\FooInterface'
。在您的控制器中,您试图创建字符串 '\App\bind\FooInterface'
。这些字符串不一样,因为它们有不同的大小写(Bind
与 bind
)。由于字符串不相同,Laravel 无法在容器中找到绑定。
更正您的 make 语句中的大小写,它应该可以工作:
dd(App::make('\App\Bind\FooInterface'));
我正在使用 Laravel 5.2。我尝试如下解决 IOCContainer 中 Laravel 中的依赖项。(使用 App::make
方法)
App/FooController.php:-
<?php
namespace App\Http\Controllers;
use App\Bind\FooInterface;
use Illuminate\Support\Facades\App;
class FooController extends Controller
{
public function outOfContainer(){
dd(App::make('\App\bind\FooInterface')); // Focus: program dies here!!
}
}
在 AppServiceProvider 中完成的 FooInterface 绑定如下
App/Providers/AppServiceProvider.php:-
<?php
namespace App\Providers;
use App\Bind\Foo;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('\App\Bind\FooInterface', function() {
return new Foo();
});
}
}
Foo 的结构class 如下。
App/Bind/Foo.php:-
<?php
namespace App\Bind;
class Foo implements FooInterface {
}
FooInterface
接口结构如下:-
<?php
namespace App\Bind;
interface FooInterface {
}
然后我创建了如下路由
Route::get('/outofcontainer', 'FooController@outOfContainer');
但是当我导航到这条路线时,它会抛出错误文本异常:
BindingResolutionException in Container.php line 748:
Target [App\bind\FooInterface] is not instantiable.
这是怎么回事? 如何将 App:make() 与 AppServiceProvider 一起使用?
在您的服务提供商中,您正在绑定字符串 '\App\Bind\FooInterface'
。在您的控制器中,您试图创建字符串 '\App\bind\FooInterface'
。这些字符串不一样,因为它们有不同的大小写(Bind
与 bind
)。由于字符串不相同,Laravel 无法在容器中找到绑定。
更正您的 make 语句中的大小写,它应该可以工作:
dd(App::make('\App\Bind\FooInterface'));