{{wikiTitle}}
核心依赖库crmeb目录说明
复制链接
编辑文档
CRMEB PRO 核心依赖库 crmeb 目录说明
一、概述
crmeb 目录是 CRMEB PRO 项目的核心依赖库,包含了系统运行所需的基础类、工具类、服务类等核心代码。这些代码为业务层提供底层支持,是二次开发的重要基础。
1.1 目录结构总览
crmeb/
├── basic/ # 基础类库(控制器、模型、驱动管理器等基类)
├── command/ # 自定义命令(artisan命令)
├── exceptions/ # 异常处理类
├── form/ # 表单构建器
├── interfaces/ # 接口定义
├── listeners/ # 事件监听器
├── services/ # 核心服务类
├── topthink/ # ThinkPHP扩展
├── traits/ # Trait特性类
└── utils/ # 工具类
二、basic 目录 - 基础类库
2.1 目录结构
crmeb/basic/
├── BaseAi.php # AI服务基类
├── BaseAuth.php # 认证授权基类(105KB核心文件)
├── BaseController.php # 控制器基类(83KB核心文件)
├── BaseDelivery.php # 配送服务基类
├── BaseErp.php # ERP对接基类
├── BaseExpress.php # 快递服务基类
├── BaseJobs.php # 队列任务基类
├── BaseManager.php # 驱动管理器基类
├── BaseMessage.php # 消息服务基类
├── BaseModel.php # 模型基类
├── BasePay.php # 支付服务基类
├── BasePrinter.php # 打印机服务基类
├── BaseProduct.php # 商品采集基类
├── BaseSmss.php # 短信服务基类
├── BaseStorage.php # 存储服务基类
└── BaseUpload.php # 上传服务基类
2.2 核心类详解
2.2.1 BaseManager - 驱动管理器基类
提供多驱动服务的统一管理能力,支持动态切换不同驱动实现。
namespace crmeb\basic;
/**
* 驱动基类
* 用于管理多驱动服务(如上传、短信、支付等)
*/
abstract class BaseManager
{
/**
* 驱动的命名空间
*/
protected string $namespace;
/**
* 配置文件名
*/
protected $configFile = null;
/**
* 已实例化的驱动
*/
protected $drivers = [];
/**
* 当前驱动名称
*/
protected $name = null;
/**
* 获取驱动实例
*/
protected function driver(string $name = null)
{
$name = $name ?: $this->name;
$name = $name ?: $this->getDefaultDriver();
return $this->drivers[$name] = $this->getDriver($name);
}
/**
* 创建驱动实例
*/
protected function createDriver(string $name)
{
$type = $this->resolveType($name);
$method = 'create' . Str::studly($type) . 'Driver';
if (method_exists($this, $method)) {
return $this->$method($name);
}
$class = $this->resolveClass($type);
return $this->invokeClass($class);
}
/**
* 设置默认驱动
*/
abstract protected function getDefaultDriver();
}
使用示例:
// 上传服务管理器
class UploadService extends BaseManager
{
protected string $namespace = '\\crmeb\\services\\upload\\';
protected function getDefaultDriver()
{
return sys_config('upload_type', 1);
}
}
// 使用方式
UploadService::instance()->upload($file); // 使用默认驱动
UploadService::instance('oss')->upload($file); // 指定OSS驱动
2.2.2 BaseJobs - 队列任务基类
所有队列任务的基类,提供任务执行的基础能力。
namespace crmeb\basic;
use think\queue\Job;
/**
* 消息队列基类
*/
abstract class BaseJobs
{
/**
* 任务执行入口
* @param Job $job 队列任务实例
* @param mixed $data 任务数据
*/
public function fire(Job $job, $data): void
{
try {
$action = $data['do'] ?? 'doJob';
$infoData = $data['data'] ?? [];
// 执行任务
$result = $this->{$action}(...$infoData);
if ($result) {
// 任务完成,删除任务
$job->delete();
} else {
// 任务失败,检查重试次数
if ($job->attempts() >= 3) {
$job->delete();
} else {
$job->release(10); // 10秒后重试
}
}
} catch (\Throwable $e) {
$job->delete();
Log::error('队列任务执行失败: ' . $e->getMessage());
}
}
/**
* 投递任务到队列
*/
public static function dispatch(string $do, array $data, string $queue = null): bool
{
$jobData = [
'do' => $do,
'data' => $data
];
return Queue::push(static::class, $jobData, $queue);
}
}
使用示例:
// 定义任务
class OrderJob extends BaseJobs
{
public function sendNotify($orderId, $userId)
{
// 发送订单通知
return true;
}
}
// 投递任务
OrderJob::dispatch('sendNotify', [$orderId, $userId], 'order_notify');
2.2.3 BaseModel - 模型基类
namespace crmeb\basic;
use think\Model;
/**
* 模型基类
*/
class BaseModel extends Model
{
/**
* 获取主键名
*/
public function getPk()
{
return $this->pk;
}
/**
* 设置数据
*/
public function setAllAttr(array $data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
return $this;
}
}
三、services 目录 - 核心服务类
3.1 目录结构
crmeb/services/
├── AccessTokenServeService.php # 访问令牌服务
├── AliPayService.php # 支付宝支付服务
├── CacheService.php # 缓存服务(核心)
├── CopyProductService.php # 商品采集服务
├── DeliverySevices.php # 配送服务
├── DownloadImageService.php # 图片下载服务
├── ExpressService.php # 快递服务
├── FileService.php # 文件服务
├── FormBuilder.php # 表单构建器
├── GroupDataService.php # 组合数据服务
├── HttpService.php # HTTP请求服务
├── LockService.php # 分布式锁服务
├── MysqlBackupService.php # MySQL备份服务
├── QrcodeService.php # 二维码服务
├── RedisService.php # Redis服务
├── SpreadsheetExcelService.php # Excel导出服务
├── SystemConfigService.php # 系统配置服务
├── UploadService.php # 上传服务
├── UtilService.php # 工具服务
├── VicWordService.php # 分词服务
├── ai/ # AI服务
├── delivery/ # 配送驱动
├── erp/ # ERP对接
├── express/ # 快递驱动
├── printer/ # 打印机驱动
├── product/ # 商品采集驱动
├── serve/ # 官方服务对接
├── sms/ # 短信服务
├── template/ # 模板消息
├── upload/ # 上传驱动
└── wechat/ # 微信服务
3.2 核心服务详解
3.2.1 CacheService - 缓存服务
提供统一的缓存操作接口,支持Redis高级特性。
namespace crmeb\services;
/**
* CRMEB 缓存服务
* 支持标签缓存、令牌桶、分布式锁等高级特性
*/
class CacheService
{
// 缓存标签名
protected static $globalCacheName = '_cached_1515146130';
// 库存队列键名映射
protected static $redisQueueKey = [
0 => 'product',
1 => 'seckill',
2 => 'bargain',
3 => 'combination',
4 => 'integral',
5 => 'discounts',
6 => 'lottery'
];
/**
* 判断缓存是否存在
*/
public static function has(string $name): bool;
/**
* 写入缓存
*/
public static function set(string $name, $value, int $expire = null): bool;
/**
* 读取缓存(支持回调函数自动写入)
*/
public static function get(string $name, $default = false, int $expire = null);
/**
* 删除缓存
*/
public static function delete(string $name);
/**
* 清空缓存
*/
public static function clear();
// ============= 令牌桶相关 =============
/**
* 设置Token令牌
*/
public static function setTokenBucket(string $key, $value, $expire = null, string $type = 'admin');
/**
* 获取Token令牌
*/
public static function getTokenBucket(string $key);
/**
* 检查Token是否存在
*/
public static function hasToken(string $key);
/**
* 清除Token
*/
public static function clearToken(string $key);
// ============= 库存队列相关 =============
/**
* 设置商品库存队列(用于秒杀等高并发场景)
* @param string $unique 商品唯一标识
* @param int $number 库存数量
* @param int $type 商品类型(0普通 1秒杀 2砍价...)
* @param bool $isPush 是否重置(true重置 false累加)
*/
public static function setStock(string $unique, int $number, int $type = 1, bool $isPush = true);
/**
* 弹出库存(扣减)
*/
public static function popStock(string $unique, int $number, int $type = 1);
/**
* 检查库存
*/
public static function checkStock(string $unique, int $number = 0, int $type = 1);
// ============= 分布式锁 =============
/**
* 设置互斥锁
*/
public static function setMutex(string $key, int $timeout = 10);
/**
* 删除互斥锁
*/
public static function delMutex(string $key);
/**
* 通用分布式锁(支持闭包)
*/
public static function lock($key, $fn = [], int $ex = 10);
/**
* 释放锁
*/
public static function unLock($key);
}
使用示例:
// 基础缓存操作
CacheService::set('user_info_1', $userInfo, 3600);
$userInfo = CacheService::get('user_info_1');
// 缓存回调(不存在时自动执行回调并写入)
$userInfo = CacheService::get('user_info_' . $uid, function() use ($uid) {
return User::find($uid)->toArray();
}, 3600);
// 秒杀库存操作
CacheService::setStock($productUniqueId, 100, 1); // 设置100件秒杀库存
CacheService::popStock($productUniqueId, 1, 1); // 扣减1件库存
$hasStock = CacheService::checkStock($productUniqueId, 1, 1); // 检查库存
// 分布式锁
CacheService::lock('order_create_' . $uid, function() {
// 创建订单的业务逻辑
return true;
});
3.2.2 SystemConfigService - 系统配置服务
namespace crmeb\services;
/**
* 系统配置服务
*/
class SystemConfigService
{
/**
* 获取单个配置值
*/
public static function get(string $key, $default = '');
/**
* 获取多个配置值
*/
public static function more(array $keys, bool $group = false): array;
/**
* 刷新配置缓存
*/
public static function clear();
}
// 全局辅助函数
function sys_config(string $key, $default = '')
{
return SystemConfigService::get($key, $default);
}
使用示例:
// 获取单个配置
$siteName = sys_config('site_name', 'CRMEB');
// 获取多个配置
$configs = SystemConfigService::more([
'site_name',
'site_logo',
'site_url'
]);
3.2.3 UploadService - 上传服务
namespace crmeb\services;
/**
* 上传服务
* 支持本地、七牛云、阿里云OSS、腾讯云COS
*/
class UploadService extends BaseManager
{
protected string $namespace = '\\crmeb\\services\\upload\\';
/**
* 获取默认驱动
*/
protected function getDefaultDriver()
{
return (int)sys_config('upload_type', 1);
}
/**
* 获取上传实例
* @param int $type 1本地 2七牛 3OSS 4COS
*/
public static function instance(int $type = null): self;
/**
* 上传文件
*/
public function upload($file, $dir = 'file');
/**
* 上传图片
*/
public function uploadImage($file, $dir = 'image');
/**
* 获取上传URL
*/
public function getUploadUrl(): string;
}
使用示例:
// 上传图片到默认存储
$result = UploadService::instance()->uploadImage($file, 'product');
// 指定上传到OSS
$result = UploadService::instance(3)->uploadImage($file, 'product');
四、traits 目录 - Trait特性类
4.1 目录结构
crmeb/traits/
├── ErrorTrait.php # 错误处理特性
├── JwtAuthModelTrait.php # JWT模型特性
├── LogicTrait.php # 逻辑层特性
├── ModelTrait.php # 模型通用特性
├── OptionTrait.php # 选项设置特性
├── QueueTrait.php # 队列特性
├── SearchDaoTrait.php # 搜索DAO特性
├── ServicesTrait.php # 服务层特性(核心)
├── api/ # API相关特性
│ └── ApiMessageTrait.php
└── service/ # 服务相关特性
└── JwtTokenTrait.php
4.2 核心Trait详解
4.2.1 ServicesTrait - 服务层特性
namespace crmeb\traits;
/**
* 服务层通用特性
* 提供分页、搜索、事务等常用功能
*/
trait ServicesTrait
{
/**
* 获取分页数据
* @param bool $isPage 是否分页
* @param bool $isRelieve 是否移除分页参数
*/
public function getPageValue(bool $isPage = true, bool $isRelieve = true);
/**
* 事务执行
* @param callable $closure 业务闭包
* @param bool $isTran 是否开启事务
*/
public function transaction(callable $closure, bool $isTran = true);
/**
* 获取搜索条件
*/
public function getSearch(array $search): array;
/**
* 创建Token
*/
public function createToken(int $id, $type, string $pwd = ''): array;
/**
* 解析Token
*/
public function parseToken(string $token): array;
}
4.2.2 SearchDaoTrait - 搜索DAO特性
namespace crmeb\traits;
/**
* 搜索DAO特性
* 提供通用搜索条件构建能力
*/
trait SearchDaoTrait
{
/**
* 设置搜索条件
*/
public function setSearch(array $where): self;
/**
* 添加Like搜索
*/
public function searchLike(string $field, $value): self;
/**
* 添加时间范围搜索
*/
public function searchTime(string $field, $time): self;
/**
* 添加状态搜索
*/
public function searchStatus($status): self;
}
五、utils 目录 - 工具类
5.1 目录结构
crmeb/utils/
├── Arr.php # 数组工具类
├── Canvas.php # 画布工具类(海报生成)
├── Captcha.php # 验证码工具
├── Date.php # 日期工具类
├── DownloadImage.php # 图片下载工具
├── ErrorCode.php # 错误码定义
├── Hook.php # 钩子工具
├── Json.php # JSON工具类
├── JwtAuth.php # JWT认证工具
├── Queue.php # 队列工具
└── Start.php # 启动工具
5.2 常用工具类
5.2.1 Arr - 数组工具类
namespace crmeb\utils;
class Arr
{
/**
* 二维数组排序
*/
public static function sortByField(array $array, string $field, int $sort = SORT_DESC): array;
/**
* 提取数组指定键值
*/
public static function getColumn(array $array, string $column, string $indexKey = null): array;
/**
* 数组转树形结构
*/
public static function toTree(array $list, string $pk = 'id', string $pid = 'pid', string $children = 'children'): array;
/**
* 递归合并数组
*/
public static function merge(array $array1, array $array2): array;
}
5.2.2 JwtAuth - JWT认证工具
namespace crmeb\utils;
use Firebase\JWT\JWT;
class JwtAuth
{
/**
* 创建Token
*/
public function createToken(array $payload, int $exp = 86400): string;
/**
* 解析Token
*/
public function parseToken(string $token): object;
/**
* 验证Token
*/
public function verifyToken(string $token): bool;
/**
* 刷新Token
*/
public function refreshToken(string $token): string;
}
六、wechat 目录 - 微信服务
6.1 目录结构
crmeb/services/wechat/
├── BaseApplication.php # 微信应用基类
├── DefaultConfig.php # 默认配置
├── MiniProgram.php # 小程序服务
├── OfficialAccount.php # 公众号服务
├── Open.php # 开放平台服务
├── Payment.php # 微信支付服务(核心)
├── Work.php # 企业微信服务
├── WechatResponse.php # 响应处理
├── config/ # 配置文件
├── live/ # 直播相关
├── mini/ # 小程序相关
├── oauth/ # OAuth认证
└── pay/ # 支付相关
6.2 Payment - 微信支付服务
namespace crmeb\services\wechat;
/**
* 微信支付服务
* 支持v2和v3版本支付接口
*/
class Payment
{
/**
* JSAPI支付(公众号/小程序)
*/
public static function jsPay(string $openid, string $orderId, string $price, string $notify, string $body): array;
/**
* 小程序支付
*/
public static function miniPay(string $openid, string $orderId, string $price, string $notify, string $body): array;
/**
* APP支付
*/
public static function appPay(string $openid, string $orderId, string $price, string $notify, string $body): array;
/**
* H5支付
*/
public static function h5Pay(string $orderId, string $price, string $notify, string $body): string;
/**
* Native扫码支付
*/
public static function nativePay(string $openid, string $orderId, string $price, string $notify, string $body): string;
/**
* 付款码支付
*/
public static function microPay(string $authCode, string $orderId, string $price, string $notify, string $body): array;
/**
* 退款
*/
public static function refund(string $orderId, string $refundNo, float $totalFee, float $refundFee, string $reason = ''): array;
/**
* 查询订单
*/
public static function query(string $orderId): array;
/**
* 关闭订单
*/
public static function close(string $orderId): bool;
}
七、其他目录
7.1 exceptions - 异常类
crmeb/exceptions/
├── AdminException.php # 后台异常
├── ApiException.php # API异常
├── AuthException.php # 认证异常
├── PayException.php # 支付异常
├── UploadException.php # 上传异常
└── WechatException.php # 微信异常
7.2 interfaces - 接口定义
crmeb/interfaces/
├── HandlerInterface.php # 处理器接口
├── ListenerInterface.php # 监听器接口
├── MiddlewareInterface.php # 中间件接口
├── ProviderInterface.php # 服务提供者接口
└── JobInterface.php # 队列任务接口
7.3 form - 表单构建器
crmeb/form/
├── Build.php # 表单构建器
├── BuildInterface.php # 构建器接口
├── FormCreate.php # 表单创建
├── Rule.php # 表单规则
├── validate/ # 验证相关
└── components/ # 表单组件
八、二次开发指南
8.1 扩展新的上传驱动
// 1. 创建驱动类 crmeb/services/upload/storage/MyStorage.php
namespace crmeb\services\upload\storage;
use crmeb\basic\BaseUpload;
class MyStorage extends BaseUpload
{
public function upload($file, $dir = '')
{
// 实现上传逻辑
}
public function delete(string $filePath): bool
{
// 实现删除逻辑
}
}
// 2. 在配置文件中注册 config/upload.php
'stores' => [
// ...
'mystorage' => [
'type' => 'MyStorage',
// 配置项
]
]
8.2 扩展新的短信驱动
// crmeb/services/sms/storage/MySmsPlatform.php
namespace crmeb\services\sms\storage;
use crmeb\basic\BaseSmss;
class MySmsPlatform extends BaseSmss
{
public function send(string $phone, string $templateId, array $data = [])
{
// 实现发送逻辑
}
}
8.3 使用缓存服务
use crmeb\services\CacheService;
// 基础缓存
CacheService::set('key', 'value', 3600);
$value = CacheService::get('key');
// 带回调的缓存
$data = CacheService::get('expensive_data', function() {
return $this->calculateExpensiveData();
}, 7200);
// 分布式锁
$result = CacheService::lock('unique_operation', function() {
return $this->doUniqueOperation();
});
九、类关系图
BaseManager (驱动管理基类)
├── UploadService (上传服务)
│ └── storage/
│ ├── Local
│ ├── Qiniu
│ ├── Oss
│ └── Cos
├── SmsService (短信服务)
├── ExpressService (快递服务)
└── PrinterService (打印服务)
BaseJobs (队列任务基类)
├── OrderCreateJob
├── SendNotifyJob
└── ProductSyncJob
ServicesTrait (服务特性)
└── BaseServices (业务服务基类)
├── UserServices
├── OrderServices
└── ProductServices
十、最佳实践
10.1 使用建议
-
不要直接修改crmeb目录下的文件
- 使用继承和组合方式扩展功能
- 通过配置文件调整行为
-
合理使用缓存服务
- 热点数据使用CacheService缓存
- 高并发场景使用分布式锁
-
遵循驱动模式扩展
- 新增驱动时继承对应基类
- 在配置文件中注册驱动
-
使用Trait复用代码
- 业务服务继承BaseServices
- 使用ServicesTrait获得通用能力
注意事项
- 不要直接修改核心类:
crmeb目录下的核心类是系统基础,直接修改会影响系统升级,应通过继承或配置方式扩展 - 驱动注册顺序:使用
BaseManager的驱动模式时,驱动需要先在配置文件中注册才能使用 - 缓存标签管理:使用
CacheService的标签功能时,注意标签的命名规范和清理时机 - 队列任务幂等性:
BaseJobs派生的队列任务应设计为幂等的,因为任务可能被重复执行 - 异常类型选择:根据业务场景选择合适的异常类型(
ApiException、AuthException、ValidateException等) - 服务层职责:
BaseServices应只处理业务逻辑,不要包含控制器相关代码或直接输出响应 - 工具类使用:
utils目录下的工具类都是静态方法调用,注意避免引入状态导致并发问题 - 表单构建器:
form目录的表单构建器生成的是前端组件配置,修改后需要清理前端缓存
常见问题
-
Q: 如何扩展上传服务支持新的云存储? A: 创建新的驱动类继承
BaseUpload,实现upload、delete等抽象方法,然后在config/upload.php中注册该驱动 -
Q: 为什么缓存设置后获取不到数据? A: 检查以下几点:1) Redis 服务是否正常运行;2) 缓存键名是否正确;3) 缓存是否设置了过短的有效期;4) 是否被其他代码清除了
-
Q: 如何自定义异常的返回格式? A: 修改
ExceptionHandle类的render方法,根据异常类型返回不同格式的响应 -
Q: 队列任务执行失败后如何重试? A: 在任务类中设置
$maxAttempts属性控制最大重试次数,通过$retryAfter设置重试间隔 -
Q: 如何在非服务类中使用 DAO 层方法? A: 通过
app()->make(XxxDao::class)获取 DAO 实例,但建议通过服务层封装后调用 -
Q:
crmeb/services和app/services有什么区别? A:crmeb/services是核心服务类(如支付、短信等基础能力),app/services是业务服务类(如订单、商品等业务逻辑)
评论({{cateWiki.comment_num}})
最新
最早
{{cateWiki.page_view_num}}人看过该文档
评论(0)
最新
最早
371人看过
登录/注册
即可发表评论
{{item.user ? item.user.nickname : ''}}
(自评)
{{item.content}}
搜索结果
为您找到{{wikiCount}}条结果
{{item.page_view_num}}
{{item.like ? item.like.like_num : 0}}
{{item.comment ? item.comment.comment_num : 0}}
位置:
{{path.name}}
{{(i+1) == getCataloguePathData(item.catalogue).length ? '':'/'}}
