Browse Source

基础搭建

master
unknown 1 year ago
parent
commit
d117b73765
  1. 25
      app/common.php
  2. 41
      app/controller/OssController.php
  3. 42
      app/controller/ResourceController.php
  4. 22
      app/exception/ModelException.php
  5. 9
      app/model/File.php
  6. 278
      app/model/Model.php
  7. 46
      app/model/Resource.php
  8. 9
      app/model/ResourceFile.php
  9. 2
      app/service.php
  10. 31
      app/service/FileSystemService.php
  11. 22
      app/service/UserService.php
  12. 43
      app/validate/ResourceValidate.php
  13. 3
      composer.json
  14. 11
      config/aliyun.php
  15. 2
      config/database.php
  16. 7
      route/app.php

25
app/common.php

@ -1,2 +1,27 @@
<?php <?php
// 应用公共文件 // 应用公共文件
/**
* 统一返回json数据
* @param $code
* @param string $msg
* @param $data
* @return \think\response\Json
*/
function jsonReturn($code, string $msg = 'success', $data = []): \think\response\Json
{
return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
}
/**
* 模型内统一数据返回
* @param $code
* @param string $msg
* @param array $data
* @return array
*/
function dataReturn($code, $msg = 'success', $data = [])
{
return ['code' => $code, 'data' => $data, 'msg' => $msg];
}

41
app/controller/OssController.php

@ -0,0 +1,41 @@
<?php
namespace app\controller;
use think\Request;
use OSS\OssClient;
use OSS\Core\OssException;
class OssController
{
public function upload()
{
$file = request()->file('file'); //接口文件的参数名,取决前端传送的参数
$filePath = $_FILES['file']['tmp_name']; //要上传文件的临时路径
$type = $file->extension();
//读取config目录下aliyun.php的aliyun_oss数据信息
$Filesystem = \think\facade\Config::get('aliyun.aliyun_oss');
dd($_FILES);
try {
$accessKeyId = $Filesystem['accessId'];
$accessKeySecret = $Filesystem['accessSecret']; //阿里云后台获取秘钥
$endpoint = $Filesystem['endpoint'];
$bucket = $Filesystem['bucket'];
//实例化对象 将配置传入
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
//这里是有sha1加密 生成文件名 之后连接上后缀
$fileName = sha1(date('YmdHis', time()) . uniqid()) . '.' . $type;
//上传至阿里云的目录 为年+月/日的格式
$pathName = date('Y-m/d') . '/' . $fileName;
$pathName = '1.jpg';
//执行阿里云上传 bucket名称,上传的目录,文件
$result = $ossClient->uploadFile($bucket, $pathName, $filePath);
} catch (OssException $e) {
return json(['code' => 0, 'message' => '上传失败', 'error' => $e->getMessage()]);
}
//将结果输出
return json(['code' => 200, 'message' => '上传成功', 'data' => $result['info']['url']]);
}
}

42
app/controller/ResourceController.php

@ -2,7 +2,11 @@
namespace app\controller; namespace app\controller;
use app\model\Resource;
use app\validate\ResourceValidate;
use think\facade\Db; use think\facade\Db;
use think\facade\Lang;
use think\exception\ValidateException;
class ResourceController class ResourceController
{ {
@ -11,7 +15,41 @@ class ResourceController
*/ */
public function index() public function index()
{ {
$result = Db::name('zl_resource')->select();
dd($result);
$resource_list = Resource::where('type', 1)->select();
// $userService = app('userService');
// return $userService->doSomething();
return jsonReturn(0, Lang::get('成功'), $resource_list);
}
public function save(Resource $resource)
{
$param = input('post.');
// 数据验证
try {
switch ($param['copyright_type']) {
case 1:
validate(ResourceValidate::class)->scene('save_selfown')->check($param);
break;
case 2:
validate(ResourceValidate::class)->scene('save_purchase')->check($param);
break;
}
} catch (ValidateException $e) {
return jsonReturn(-1, $e->getError());
}
//保存到数据库
Db::startTrans();
try {
// 1. 保存站点到数据库
$res = $resource->addResource($param);
Db::commit();
} catch (\Exception $e) {
Db::rollback();
return jsonReturn(-5, $e->getMessage());
}
return json($res);
} }
} }

22
app/exception/ModelException.php

@ -0,0 +1,22 @@
<?php
namespace app\exception;
class ModelException extends BaseException
{
protected $errCode = 50001;
protected $errMsg = '模型方法错误';
public function __construct($msg = null,$code = null)
{
if(!$msg){
$msg = $this->errMsg;
}
if(!$code){
$code = $this->errCode;
}
parent::__construct($msg,$code);
}
}

9
app/model/File.php

@ -0,0 +1,9 @@
<?php
namespace app\model;
use app\exception\ModelException;
class File extends Model
{
}

278
app/model/Model.php

@ -0,0 +1,278 @@
<?php
declare(strict_types=1);
namespace app\model;
use app\exception\ModelEmptyException;
use app\exception\ModelException;
use app\exception\ModelNotUniqueException;
use app\service\CacheService;
use think\facade\Cache;
use think\Model as BaseModel;
/**
* @mixin \think\Model
*/
class Model extends BaseModel
{
// msg
public $getMsg;
public $addMsg;
public $updateMsg;
public $delMsg;
// 成功编码
public $sucCode = 0;
// 软删除数据
public $delData;
// 错误编码
public $errorCode = '50011';
public $listCacheKey;
public $detailCacheKey;
public $className;
protected $hidden = [
'password', 'seller_id'
];
public function __construct($data = [])
{
$this->delData = [
'is_del' => 2,
'delete_time' => time(),
'update_time' => time(),
];
$this->className = $this->getClassName();
$this->listCacheKey = $this->className . '_cache_list';
$this->detailCacheKey = $this->className . '_cache_detail';
$this->getMsg = lang('获取成功');
$this->addMsg = lang('添加成功');
$this->updateMsg = lang('修改成功');
$this->delMsg = lang('删除成功');
parent::__construct($data);
}
/**
* @param array $where
* @return array
*/
public function getCustomDataColumn($column, array $where = []): array
{
try {
$res = $this->where($where)->column($column);
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->getMsg, $res);
}
/**
* @param array $where
* @param int $limit
* @return array
*/
public function getCustomDataList(array $where = [], int $limit = 10, $order = 'id desc', $field = "*"): array
{
try {
$res = $this->field($field)->where($where)->order($order)->paginate($limit);
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->getMsg, $res);
}
public function getLimitCustomData($where, $order = 'id desc', $limit = 10, $field = "*", $with = [], $offset = 0): array
{
$key = md5($this->className . json_encode([$where, $order, $limit, $field, $with, $offset]));
$res = Cache::get($key);
if (!empty($res)) {
return dataReturn($this->sucCode, $this->getMsg, json_decode($res, true));
}
try {
$res = $this->field($field)->with($with)->where($where)->order($order)->limit($offset, $limit)->select()->toArray();
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
Cache::set($key, json_encode($res));
CacheService::append($this->listCacheKey, $key);
return dataReturn($this->sucCode, $this->getMsg, $res);
}
public function getAllCustomArrayData($where, $order = 'id desc', $field = "*", $with = [], $offset = 0): array
{
$key = md5($this->className . json_encode([$where, $order, $field, $with]));
$res = Cache::get($key);
if (!empty($res)) {
return dataReturn($this->sucCode, $this->getMsg, json_decode($res, true));
}
try {
$res = [];
if ($offset <= 0) {
$res = $this->field($field)->with($with)->where($where)->order($order)->select()->toArray();
} else {
$count = $this->field($field)->with($with)->where($where)->count();
$last = (int)bcsub((string)$count, (string)$offset);
if ($last > 0) {
$res = $this->field($field)->with($with)->where($where)->order($order)->limit($offset, $last)->select()->toArray();
}
}
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
Cache::set($key, json_encode($res));
CacheService::append($this->listCacheKey, $key);
return dataReturn($this->sucCode, $this->getMsg, $res);
}
public function getAllCustomDataModel($where, $order = 'id desc', $field = "*", $with = []): array
{
try {
$res = $this->field($field)->with($with)->where($where)->order($order)->select();
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->getMsg, $res);
}
/**
* @param array $name
* @return array
*/
public function getCustomData(array $name = [], $with = [], $field = "*"): array
{
try {
$res = $this->with($with)->field($field)->where($name)->find();
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->getMsg, $res);
}
/**
* @param array $where
* @return array with
* @throws ModelEmptyException
* @throws ModelException
*/
public function getCustomArrayData(array $where = [], $with = [], string $field = '*'): array
{
$key = md5($this->className . json_encode([$where, $field, $with]));
$res = Cache::get($key);
if (!empty($res)) {
return dataReturn($this->sucCode, $this->getMsg, json_decode($res, true));
}
try {
$res = $this->field($field)->with($with)->where($where)->findOrEmpty()->toArray();
if (empty($res)) {
throw new ModelEmptyException();
}
} catch (ModelEmptyException $me) {
throw new ModelEmptyException();
} catch (\Exception $e) {
throw new ModelException($e->getMessage());
}
Cache::set($key, json_encode($res));
CacheService::append($this->listCacheKey, $key);
return dataReturn($this->sucCode, $this->getMsg, $res);
}
/**
* @param $param
* @return array
*/
public function addCustomData($param): array
{
try {
$res = self::create($param);
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->addMsg, $res);
}
/**
* @param $param
* @return array
*/
public function addAllCustomData($param): array
{
try {
$res = self::saveAll($param);
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->addMsg, $res);
}
/**
* @param array $where
* @param $param
* @return array
*/
public function updateCustomData(array $where, $param, $strict = true): array
{
try {
$res = self::strict($strict)->where($where)->update($param);
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->updateMsg, $res);
}
/**
* @param $where
* @return array
*/
public function delCustomData($where): array
{
try {
$res = self::where($where)->delete();
} catch (\Exception $e) {
return dataReturn($this->errorCode, $e->getMessage());
}
return dataReturn($this->sucCode, $this->delMsg, $res);
}
/**
* @throws ModelNotUniqueException
* @throws ModelException
*/
public function saveUnique($where, $msg = '')
{
try {
$res = $this->where($where)->find();
} catch (\Exception $e) {
throw new ModelException($e->getMessage());
}
if (!empty($res)) {
throw new ModelNotUniqueException(!empty($msg) ? $msg : lang('内容已存在'));
}
}
/**
* @throws ModelException
* @throws ModelNotUniqueException
*/
public function updateUnique($where, $id, $msg = '')
{
try {
$res = $this->where($where)->find();
} catch (\Exception $e) {
throw new ModelException($e->getMessage());
}
if (!empty($res) && $res['id'] != $id) {
throw new ModelNotUniqueException(!empty($msg) ? $msg : lang('内容已存在'));
}
}
public function getClassName(): string
{
$reflection = new \ReflectionClass($this);
return $reflection->getShortName();
}
}

46
app/model/Resource.php

@ -0,0 +1,46 @@
<?php
namespace app\model;
use app\exception\ModelException;
class Resource extends Model
{
/**
* @param $param
* @return array
* @throws ModelException
*/
public function addResource($param): array
{
try {
//插入资源表
$resource_res = self::create($param);
//插入素材表 添加素材录入方式 并获取插入后的ids
$file_obj = new File();
foreach ($param['file'] as $file) {
$file['file_input_mode'] = $param['file_input_mode'];
$file_array[] = $file;
}
$file_res = $file_obj->saveAll($file_array);
foreach ($file_res as $item) {
$file_ids[] = $item->id;
}
//插入资源素材关联表
foreach ($file_ids as $file_id) {
$resource_file_array[] = [
'resource_id' => $resource_res->id,
'file_id' => $file_id,
];
}
$ResourceFile = new ResourceFile();
$ResourceFile->saveAll($resource_file_array);
} catch (\Exception $e) {
throw new ModelException($e->getMessage());
}
return dataReturn($this->sucCode, $this->addMsg, $resource_res->id);
}
}

9
app/model/ResourceFile.php

@ -0,0 +1,9 @@
<?php
namespace app\model;
use app\exception\ModelException;
class ResourceFile extends Model
{
}

2
app/service.php

@ -5,5 +5,5 @@ use app\AppService;
// 系统服务定义文件 // 系统服务定义文件
// 服务在完成全局初始化之后执行 // 服务在完成全局初始化之后执行
return [ return [
AppService::class,
// 'app\service\FileSystemService',
]; ];

31
app/service/FileSystemService.php

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace app\service;
class FileSystemService extends \think\Service
{
/**
* 注册服务
*
* @return mixed
*/
public function register()
{
//
//手动修改的
echo 'FileSystemService-register()';
}
/**
* 执行服务
*
* @return mixed
*/
public function boot()
{
//手动修改的
echo 'FileSystemService-boot()';
}
}

22
app/service/UserService.php

@ -0,0 +1,22 @@
<?php
// application/service/UserService.php
namespace app\service;
use think\Service;
class UserService extends Service
{
// public function register()
// {
// // 注册服务时执行的逻辑,例如绑定到容器
// $this->app->bind('userService', function () {
// return new UserService();
// });
// }
public function doSomething()
{
// 服务的具体方法
return 'Service is working';
}
}

43
app/validate/ResourceValidate.php

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace app\validate;
use think\Validate;
class ResourceValidate extends Validate
{
/**
* 定义验证规则
* 格式:'字段名' => ['规则1','规则2'...]
*
* @var array
*/
protected $rule = [
'name|资源名称' => 'require',
'resource_type|资源类型' => 'require',
'accredit_main_body|被授权主体' => 'require',
'supplier|供应商' => 'require',
'price|价格' => 'require|number',
'accredit_file_number|授权文件号码' => 'require',
"use_range|适用范围" => 'require',
"file_input_mode|素材录入方式" => 'require',
"file|素材" => 'require',
];
protected $scene = [
'save_purchase' => ['name', 'resource_type', 'accredit_main_body', 'supplier', 'price', 'accredit_file_number', 'use_range', 'file_input_mode', 'file'],
'save_selfown' => ['name', 'resource_type', 'file_input_mode', 'file'],
// 'update' => ['id', 'title', 'domain', 'parent_id'],
// 'setStatus' => ['id', 'status'],
];
// // 验证域名格式
// protected function validateDomain($value)
// {
// // 正则表达式验证域名或 IP 地址加端口号
// $pattern = '/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[a-z0-9]+(?:-[a-z0-9]+)*)\.)+[a-z]{2,}|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::\d{2,5})?(?:\/[^\s]*)?$/i';
// return preg_match($pattern, $value) ? true : lang('域名格式错误');
// }
}

3
composer.json

@ -23,7 +23,8 @@
"php": ">=8.0.0", "php": ">=8.0.0",
"topthink/framework": "^8.0", "topthink/framework": "^8.0",
"topthink/think-orm": "^3.0", "topthink/think-orm": "^3.0",
"topthink/think-filesystem": "^2.0"
"topthink/think-filesystem": "^2.0",
"aliyuncs/oss-sdk-php": "^2.7"
}, },
"require-dev": { "require-dev": {
"symfony/var-dumper": ">=4.2", "symfony/var-dumper": ">=4.2",

11
config/aliyun.php

@ -0,0 +1,11 @@
<?php
return [
'aliyun_oss' => [
'type' => 'aliyun',
'accessId' => 'LTAI5tLf2yHfxGvXPMHRR7cn',
'accessSecret' => 'vMQLKxqwX7KjxOh5peLSTFscyWl2Z9',
'bucket' => 'zailiu-test',
'endpoint' => 'oss-cn-beijing.aliyuncs.com', // 节点
'url' => '', //不要斜杠结尾,此处为URL地址域名。
],
];

2
config/database.php

@ -38,7 +38,7 @@ return [
// 数据库编码默认采用utf8 // 数据库编码默认采用utf8
'charset' => env('DB_CHARSET', 'utf8'), 'charset' => env('DB_CHARSET', 'utf8'),
// 数据库表前缀 // 数据库表前缀
'prefix' => env('DB_PREFIX', ''),
'prefix' => env('DB_PREFIX', 'zl_'),
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0, 'deploy' => 0,

7
route/app.php

@ -17,5 +17,10 @@ Route::get('think', function () {
Route::get('hello/:name', 'index/hello'); Route::get('hello/:name', 'index/hello');
Route::group('resource', function () { Route::group('resource', function () {
Route::rule('index', 'resource/index');
Route::post('/save', 'resource/save');
Route::rule('/index', 'resource/index');
});
Route::group('oss', function () {
Route::post('/upload', 'oss/upload');
}); });
Loading…
Cancel
Save