Laravel 依赖注入基础与类注入示例
Laravel 框架具备自动解析并注入所需依赖的能力,但在处理自定义类与接口时,其机制存在显著差异。
针对具体的类,Laravel 容器通常能自动完成注入;而对于接口,则必须创建一个 Service Provider 来建立接口与其具体实现类之间的绑定关系。此外,还需将该 Service Provider 注册至 `config/app.php` 文件的 `providers` 数组中,以便容器明确知晓应注入哪个具体实现。
首先,我们定义一个名为 `myClass` 的自定义类。
该类位于命名空间 `App\library` 下。
class myClass {
public function show() {
echo __FUNCTION__.' Hello World';
}
}
接下来,在路由文件中设置访问路径。
Route::get('test/ioc', 'TestController@index');
同时修改 `TestController` 控制器以使用依赖注入。
class TestController extends Controller
{
public function index(myClass $myClass) {
$myClass->show();
}
}
访问 `http://localhost/test/ioc` 地址后,页面能够成功打印出 `show Hello World`。
接口注入的错误与 Service Provider 配置
随后,我们对 `myClass` 进行修改,使其实现某个接口。
class myClass implements like {
public function play() {
// TODO: Implement play() method.
echo __FUNCTION__.' Hello Play';
}
}
这里定义的接口名为 `like`。
interface like {
public function play();
}
接着调整 `TestController` 中的代码,尝试注入该接口。
class TestController extends Controller
{
public function index(like $like) {
$like->play();
}
}
如果此时再次访问上述地址,系统会提示错误信息。
Target [App\library\like] is not instantiable.
对于接口的注入,必须在对应的 Service Provider 的 `register` 方法中进行注册声明,并确保该 Service Provider 已写入 `config/app` 的 `providers` 数组中。
我们需要定义一个名为 `LikeServiceProvider` 的服务提供者类。
class LikeServiceProvider extends ServiceProvider
{
public function boot()
{
//
}
public function register()
{
//
$this->app->bind('App\library\like', 'App\library\myClass');
}
}
之后,必须将 `LikeServiceProvider` 添加到 `config\app.php` 文件的 `providers` 数组中。
继续访问之前的地址,页面现在能够成功输出 `play Hello Play`。
以上关于 Laravel 类和接口注入相关的代码分享完毕,希望能为大家提供参考,也希望大家多多支持本站。