Laravel 类和接口注入相关的代码

2020-09-04 08:09:34

Laravel能够自动注入需要的依赖,对于自定义的类和接口是有些不同的。

对于类,Laravel可以自动注入,但是接口的话需要创建相应的ServiceProvider注册接口和实现类的绑定,同时需要将ServiceProvider添加到congif/app.php的providers数组中,这样容器就能知道你需要注入哪个实现。

现在自定义一个类myClass

namespace Applibrary;

class myClass { public function show() {  echo __FUNCTION__.' Hello World'; }}

设置route

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。

修改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 [Applibrarylike] is not instantiable.

对于接口注入,我们需要在对应的ServiceProvider的register方法中注册,并将对应的ServiceProvider写入config/app的providers数组中。

定义LikeServiceProvider

class LikeServiceProvider extends ServiceProvider{ public function boot() {  // } public function register() {  //  $this->app->bind('Applibrarylike', 'ApplibrarymyClass'); }}

之后我们需要将LikeServiceProvider添加到configapp.php文件的providers数组中。

还是继续访问上述的地址,页面成功输出play Hello Play。

相关文章 大家在看