Laravel 類和接口注入相關(guān)的代碼
Laravel能夠自動(dòng)注入需要的依賴,對(duì)于自定義的類和接口是有些不同的。
對(duì)于類,Laravel可以自動(dòng)注入,但是接口的話需要?jiǎng)?chuàng)建相應(yīng)的ServiceProvider注冊(cè)接口和實(shí)現(xiàn)類的綁定,同時(shí)需要將ServiceProvider添加到congif/app.php的providers數(shù)組中,這樣容器就能知道你需要注入哪個(gè)實(shí)現(xiàn)。
現(xiàn)在自定義一個(gè)類myClass
namespace App\library;
class myClass {
public function show() {
echo __FUNCTION__.' Hello World';
}
}
設(shè)置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();
}
}
如果還是訪問上面的地址,會(huì)提示錯(cuò)誤
Target [App\library\like] is not instantiable.
對(duì)于接口注入,我們需要在對(duì)應(yīng)的ServiceProvider的register方法中注冊(cè),并將對(duì)應(yīng)的ServiceProvider寫入config/app的providers數(shù)組中。
定義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數(shù)組中。
還是繼續(xù)訪問上述的地址,頁(yè)面成功輸出play Hello Play。
以上這篇Laravel 類和接口注入相關(guān)的代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
php生成N個(gè)不重復(fù)的隨機(jī)數(shù)實(shí)例
使用php生成N個(gè)不重復(fù)的隨機(jī)數(shù)的實(shí)例方法2013-11-11
php數(shù)據(jù)序列化測(cè)試實(shí)例詳解
這篇文章主要介紹了php數(shù)據(jù)序列化測(cè)試實(shí)例詳解的相關(guān)資料,主要介紹msgpack、json、serialize對(duì)比,需要的朋友可以參考下2017-08-08
簡(jiǎn)單易用的php數(shù)據(jù)庫(kù)pdo操作類(curd?demo)
這篇文章主要介紹了簡(jiǎn)單易用的php數(shù)據(jù)庫(kù)pdo操作類(curd?demo),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
PHP面向?qū)ο笾I(lǐng)域模型+數(shù)據(jù)映射器實(shí)例(分析)
下面小編就為大家?guī)硪黄狿HP面向?qū)ο笾I(lǐng)域模型+數(shù)據(jù)映射器實(shí)例(分析)。小編覺得挺不錯(cuò)的。現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
Laravel 5框架學(xué)習(xí)之Laravel入門和新建項(xiàng)目
這篇文章主要是Laravel5框架學(xué)習(xí)系列的第一篇文章,跟其他開篇文章一樣,我們來學(xué)習(xí)下Laravel入門和新建項(xiàng)目,十分的簡(jiǎn)單易懂,有需要的小伙伴可以參考下。2015-04-04

