一、自定义类
新建文件:App\demo\fx.php
<?php
namespace App\demo;
class fx{
public function show(){
echo 'my name is wz';
}
}
二、将fx类绑定到容器:
首先用artisan命令创建服务者:php artisan make:provider myServiceProvider
然后绑定自定义类fx
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\demo\fx;
class myServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('fx',function(){
return new fx;
});
}
}
三、将服务者myServiceProvider注册到config\app.php中:
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\myServiceProvider::class,
四、控制器中实现依赖注入
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\demo\fx;
class index extends Controller
{
//
public function index(fx $fx){
$fx->show();
}
}
网友评论