PHP 服务契约,laravel 契约的使用

本文探讨了契约(接口)在 Laravel 框架中的实际运用,对比接口和实例化类的区别,重点讲解了如何在服务容器中注册和注入接口。作者分享了将接口绑定到具体实现类的方法,以及如何在控制器中通过依赖注入灵活使用接口。
摘要由CSDN通过智能技术生成

契约的使用这方面很少文章介绍,很多文章都是直接翻译了文档,并没有提到实际中的使用。

个人理解的契约就是接口,那么他的使用其实是应该类似于写观察者模式时候一样,方法中的参数使用的是接口,但实际传参的时候,用的是实例化接口的类。

在服务容器那一个章节,有这个一个介绍

先写一个接口和两个实例化的类

namespace App;

interface BookInterface

{

public function getCurrentPage();

}

namespace App;

class EBook implements BookInterface

{

public function getCurrentPage()

{

return 'EBook current page';

}

}

namespace App;

class PaperBook implements BookInterface

{

public function getCurrentPage()

{

return 'paper current page';

}

}

$this->app->bind(

'App\Contracts\EventPusher',

'App\Services\RedisEventPusher'

);

原本想着直接在一个方法中这样写 app()->bind(BookInterface::class,PaperBook::class); 但测试后发现不行,

必须写到 App\Providers 目录下的文件夹中 register方法里才可以

namespace App\Providers;

use App\BookInterface;

use App\EBook;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider

{

public function register()

{

$this->app->bind(BookInterface::class,EBook::class);

}

}

现在如果在一个方法中直接注入 BookInterface 接口,会默认使用 EBook 这个类

public function index(BookInterface $book)

{

dd($book->getCurrentPage()); // EBook current page

}

另一种实现方式就比较好理解

public function index()

{

return $this->getPage(new EBook());

}

public function getPage(BookInterface $book)

{

return $book->getCurrentPage();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值