BaseService.php
1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
/**
* @author:wlj
* @date: 2022/6/30 15:44
*/
namespace App\Services;
use App\Enums\Common\Code;
use App\Exceptions\BsideGlobalException;
use Mockery;
class BaseService
{
/**
* 单例模式
* 特点:三私,两静,一公
* 三私:三个私有方法,(静态变量、构造函数、克隆函数)
* 两静:两个静态方法,(一个静态变量,一个静态方法)
* 一公:单例模式的出口
*
* 优点:
* 1、在内存里只有一个实例,减少了内存的开销,尤其是频繁的创建和销毁实例(比如管理学院首页页面缓存)。
* 2、避免对资源的多重占用(比如写文件操作)。
*/
protected static $instance;
/**
* @return static
*/
public static function getInstance()
{
if ((static::$instance[static::class] ?? null) instanceof static) {
return static::$instance[static::class];
}
return static::$instance[static::class] = new static();
}
/**
* @return Mockery\Mock
*/
public static function mockInstance()
{
return static::$instance[static::class] = Mockery::mock(static::class)
->makePartial()
->shouldAllowMockingProtectedMethods();
}
private function __construct()
{
}
private function __clone()
{
// TODO: Implement __clone() method.
}
/**
* @notes: 手动抛出异常
* @param string $msg
* @param string $code
* @throws BsideGlobalException
* @author:wlj
* @date: 2022/7/19 14:25
*/
public function fail(string $msg, string $code = Code::SYSTEM_ERROR)
{
throw new BsideGlobalException($code, $msg);
}
}