Laravel-Providers

一、手动创建服务

1.创建服务

# routes/web.php
# 创建接口
interface Food
{
    public function weight();
}
# 实现接口类
class Apple implements Food
{
    public $weight;

    public function __construct($weight)
    {
        $this->weight = $weight;
    }

    public function weight()
    {
        return $this->weight;
    }
}

2.绑定服务

# 绑定方式一
app()->bind('yuan', function () {
    return new Apple(18);
});

Route::get('d1', function () {
    dd(resolve('yuan'));
});

# 访问路由输出:18
# 绑定方式二
app()->bind('Food', 'Apple');
app()->when('Apple')->needs('$weight')->give('100');

Route::get('d1',function (){
    dd(app('Food'));
});
# 访问路由输出:100

二、Laravel服务创建

3.Laravel创建服务

php artisan make:provider DemoServiceProvider

4.注册服务

# 1.创建好的文件在 app/Providers/ 文件中
# 2.配置文件中注册服务 config/app.php
'providers' => [
    App\Providers\DemoServiceProvider::class
],

5.绑定服务

 public function register()
    {
        //
        $this->app->bind('Demo', function () {
            return 'Demo';
        });
    }

#路由访问
Route::get('d2',function (){
    dd(resolve('Demo'));
});
#输出:Demo

三、Laravel中使用

6.创建接口和实现类

# app/Http/Controllers/Food.php
namespace App\Http\Controllers;


interface Food
{
    public function weight();
}
# app/Http/Controllers/Apple.php
namespace App\Http\Controllers;


class Apple implements Food
{

    public $weight;

    public function __construct($weight)
    {
        $this->weight = $weight;
    }

    public function weight()
    {
        // TODO: Implement weight() method.
        return $this->weight();
    }
}

7.绑定服务

# app/Providers/DemoServiceProvider.php
# 1.视频中写法
$this->app->bind('Food', 'Apple');
$this->app->when('Apple')->needs('$weight')->give('0101');

# 2.路由访问
Route::get('d2',function (){
    dd(app('Food'));
});

# 3.报错
Target class [Apple] does not exist

# 4.暂时未解决
/* 欢迎大神指点迷津 */

# 5.采用另一种方式注册
$this->app->bind('Food', function () {
    return new Apple(18);
});

# 6.或者
$weight = 15;
$this->app->singleton('Food', function ($app) use ($weight) {
    return new Apple($weight);
});

8.服务懒加载

# laravel中服务会被主动加载耗费资源,采用懒加载模式
# 实现 DeferrableProvider
# 返回 provides
class DemoServiceProvider extends ServiceProvider implements DeferrableProvider
{
 public function provides()
    {
        return [Food::class];
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值