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


  • 2019-08-30 21:53:51

    OpenSSL实践-Android下的编译和使用

    openssl可以编译成ARM下面的二进制代码(动态库或者静态库),方便APP使用,APP在使用的时候,需要使用JNI来进行调用。

  • 2019-08-31 14:05:00

    JNI Crash:异常定位与捕获处理

    在Android JNI开发中,经常会遇到JNI崩溃的问题,尤其带代码量大,或者嵌入了第三方代码的情况下,很难进行问题定位和处理。本文将介绍两种常见的JNI崩溃处理方法,包括: 每个JNI调用后进行异常检测处理(适用于JNI代码量很小的情况) 捕获系统崩溃的Signal,并进行异常处理(适用于JNI代码量大,难以每句话后面都进行异常检测的情况)