laravel singleton和bind方法的区别

2020-02-19 23:58:51

参考地址 laravel学习笔记(七)singleton和bind方法的区别

singleton和bind都是返回一个类的实例,不同的是singleton是单例模式,而bind是每次返回一个新的实例。

1、singleton

1
2
3
4
5
6
7
8
9
10
class fun {
    public $strKey;
}
 
app()->singleton('fun', fun::class);
$fun1 = app()->make('fun');
$fun2 = app()->make('fun');
$fun1->strKey = "fun1";
$fun2->strKey = "fun2";
echo $fun1->strKey . '  ' $fun2->strKey;

  最后获取到的结果是fun2 fun2

2、bind

1
2
3
4
5
6
7
8
9
10
class fun {
    public $strKey;
}
 
app()->bind('fun', fun::class);
$fun1 = app()->make('fun');
$fun2 = app()->make('fun');
$fun1->strKey = "fun1";
$fun2->strKey = "fun2";
echo $fun1->strKey . '  ' $fun2->strKey;

  最后获取到的结果是fun1 fun2

再看框架底层代码:

1
2
3
4
public function singleton($abstract$concrete = null)
{
    $this->bind($abstract$concrete, true);
}

发现singleton方法其实也是调用bind方法,只是最后一个参数是true,表示单例模式。框架源代码:Illuminate/Container/Container.php


  • 2018-06-02 00:29:58

    Android实现沉浸式状态栏的那些坑

    最近项目需要实现沉浸式的状态栏,其实我在之前就了解过Android的沉浸式,发现有些棘手就放弃了,但是此次是公司的项目需要的,就花了几天把这个问题搞定了,在此记录一下,并mark几个坑。 首先,沉浸式是Android 4.4及以上才有的,在后续的5.0及6.0上面都增加了一些相关支持,于是问题就不太好办了。先看我实现的效果:

  • 2018-06-02 00:30:35

    Android 解决沉浸式状态栏下,输入法弹出,布局不会自动调整的BUG

    在开发中,如果输入框在布局的底部。在弹出输入发时,为了使输入法不遮挡输入框通常有两种做法: 1.将布局压缩(Activity的android:windowSoftInputMode属性设置为”adjustResize”)。 2.移动布局,将布局顶到输入框之上(Activity的android:windowSoftInputMode属性设置为”adjustPan”)

  • 2018-06-02 00:31:27

    Android layout实现输入法弹出后,布局整体上移

    那如果要实现沉浸式状态栏又要保持布局不会被输入法遮挡,怎么办呢? 只要在根布局加上android:fitsSystemWindows=”true”即可,效果如下(为方便看效果我把背景改成了黄色):

  • 2018-06-04 10:06:43

    mysql查询数据的同时对它进行删除操作

    今天遇见一个问题,需要把mysql数据库里面的 商品主表 和它的每一个条目对应不上的数据给全部删除(数据如下图);也就是整理一下数据库里的数据保证数据的可用;