Skip to content

Commit 7be2957

Browse files
committed
update
1 parent 529b234 commit 7be2957

File tree

1 file changed

+71
-1
lines changed

1 file changed

+71
-1
lines changed

src/DatabaseFactory.php

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ final class DatabaseFactory implements DatabaseInterface
2323
{
2424
private DatabaseInterface $driver;
2525

26+
/** @var array<string, mixed> 模型实例缓存池 */
27+
private array $modelCache = [];
28+
2629
/**
2730
* @param array $config 数据库配置
2831
* @param string $ormType ORM类型 ('laravelORM', 'thinkORM')
@@ -42,13 +45,80 @@ public function __construct(
4245
};
4346
}
4447

48+
/**
49+
* 快速获取 QueryBuilder(工厂应实现 builder())
50+
* 如果底层不支持 builder(),退回 make()
51+
*/
52+
public function builder(string $modelClass): mixed
53+
{
54+
if (method_exists($this->driver, 'builder')) {
55+
return $this->driver->builder($modelClass);
56+
}
57+
return $this->make($modelClass);
58+
}
59+
60+
/**
61+
* 直接获取“新模型”实例(非 builder)
62+
*/
63+
public function newModel(string $modelClass): mixed
64+
{
65+
if (method_exists($this->driver, 'newModel')) {
66+
return $this->driver->newModel($modelClass);
67+
}
68+
return $this->make($modelClass);
69+
}
70+
71+
/**
72+
* 驱动判定,Repository 使用此 API 而不是 instanceof
73+
*/
74+
public function isEloquent(): bool
75+
{
76+
return $this->driver instanceof EloquentFactory;
77+
}
78+
79+
public function isThink(): bool
80+
{
81+
return $this->driver instanceof ThinkORMFactory;
82+
}
83+
84+
/**
85+
* 判断给定 modelClass 是否为 ORM 模型(由 driver 识别)
86+
*/
87+
public function isModel(string $modelClass): bool
88+
{
89+
if (method_exists($this->driver, 'isModel')) {
90+
return $this->driver->isModel($modelClass);
91+
}
92+
// 兜底:检查类是否为常见 ORM 基类子类
93+
if (class_exists($modelClass)) {
94+
return is_subclass_of($modelClass, '\Illuminate\Database\Eloquent\Model')
95+
|| is_subclass_of($modelClass, '\think\Model');
96+
}
97+
return false;
98+
}
99+
100+
45101
public function __invoke(string $modelClass): mixed
46102
{
47103
return $this->driver->make($modelClass);
48104
}
49105

106+
/**
107+
* 缓存模型实例,避免重复 new Model()
108+
*/
50109
public function make(string $modelClass): mixed
51110
{
52-
return $this->driver->make($modelClass);
111+
// 表名模式(不是 class),直接跳缓存
112+
if (!class_exists($modelClass)) {
113+
return $this->driver->make($modelClass);
114+
}
115+
116+
// 模型缓存
117+
if (!isset($this->modelCache[$modelClass])) {
118+
$this->modelCache[$modelClass] = $this->driver->make($modelClass);
119+
}
120+
121+
// 每次返回 clone,避免污染 query builder
122+
return $this->modelCache[$modelClass];
53123
}
54124
}

0 commit comments

Comments
 (0)