### Install Form Component Source: https://doc.catchadmin.vip/start/upgrade Install the CatchAdmin form component using Composer to enable quick CURD building. ```shell # 获取组件 composer require catchadmin/form ``` -------------------------------- ### Standard Module Directory Structure Example Source: https://doc.catchadmin.vip/start/rules Illustrates the standard directory structure for a modular component in CatchAdmin, using the 'permissions' module as an example. Shows organization for database files, exceptions, middlewares, providers, routes, HTTP layer, and models. ```text ├─permissions │ ├─database # 数据库相关文件 │ │ ├─migrations # 数据库迁移文件 │ │ └─seeders # 数据填充文件 │ ├─Exceptions # 模块专用异常类 │ ├─Middlewares # 模块中间件 │ ├─Providers # 服务提供者 │ ├─routes # 模块路由定义 │ ├─HTTP # HTTP层业务逻辑 │ │ ├─Controllers # 控制器类 │ │ └─Requests # 表单验证请求类 │ └─Models # 数据模型类 ├─Installer.php # 模块安装器 ``` -------------------------------- ### Generate and Serve Documentation Source: https://doc.catchadmin.vip/start/api Commands to generate the API documentation and start the Vitepress development server. ```shell php artisan catch:api:doc ``` ```php yarn install // 启动文档 yarn docs:dev ``` -------------------------------- ### Annotation Syntax Examples Source: https://doc.catchadmin.vip/start/api Standard syntax for defining various API parameters in Docblocks. ```text @urlParam 字段名 类型 [required(可选)] 注释 ``` ```text @bodyParam 字段名 类型 [required(可选)] 注释 ``` ```text @responseField 字段名 类型 注释 ``` ```text @queryParam 字段名 类型 [required(可选)] 注释 ``` -------------------------------- ### Package Project with CatchAdmin CLI Source: https://doc.catchadmin.vip/start/bt-deploy Use this command to package your CatchAdmin project for deployment. Follow the prompts for necessary information. The output is a `project.zip` file in the root directory. Ensure your domain starts with `https`. ```shell php artisan catch:build ``` -------------------------------- ### Install JWT Auth Package Source: https://doc.catchadmin.vip/start/app Install the JWT authentication package using Composer for CatchAdmin versions below 3.2.0. ```shell composer require "tymon/jwt-auth" ``` -------------------------------- ### Publish JWT Configuration Source: https://doc.catchadmin.vip/start/app Publish the JWT configuration file after installing the package. ```shell php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" ``` -------------------------------- ### PUT /users/{id} Source: https://doc.catchadmin.vip/start/api Example of documenting an update user endpoint using Scribe annotations. ```APIDOC ## PUT /users/{id} ### Description Updates an existing user's information. ### Method PUT ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (int) - Required - User ID #### Request Body - **username** (string) - Required - Username - **password** (string) - Optional - Password - **email** (string) - Optional - Email - **mobile** (string) - Optional - Mobile number - **department_id** (int) - Optional - Department ID - **roles** (integer[]) - Optional - List of role IDs - **jobs** (integer[]) - Optional - List of job IDs ### Response #### Success Response (200) - **data** (bool) - Whether the update was successful ``` -------------------------------- ### Initialize Permissions and Menus Source: https://doc.catchadmin.vip/start/bt-deploy Execute this command to seed the database with necessary permissions and menu structures. Verify your PHP path is correct. ```shell # 初始化权限菜单 /www/server/php/82/bin/php artisan catch:db:seed permissions ``` -------------------------------- ### Initialize Super Administrator Source: https://doc.catchadmin.vip/start/bt-deploy Run this command to seed the database with a super administrator account. Ensure your PHP version and path are correctly specified. ```shell # 初始化超级管理员 /www/server/php/82/bin/php artisan catch:db:seed user ``` -------------------------------- ### 配置全局异常处理器 Source: https://doc.catchadmin.vip/start/app 在 bootstrap/app.php 中配置 withExceptions 方法,将异常渲染为统一的 JSON 格式。 ```php ->withExceptions(function (Exceptions $exceptions) { $exceptions->render(function (Throwable $exception, Request $request) { // 渲染 app 异常,返回错误信息 if ($exception instanceof ApiAppException) { return ApiResponse::error($exception->getMessage(), $exception->getCode()); } // 其他系统异常自行处理, 请根据项目实际情况进行处理 // 如果路由前缀使用 api/app 则返回 api app 异常 if ($request->route()->prefix('api/app')) { return ApiResponse::error($exception->getMessage(), $exception->getCode()); } }); }) ``` -------------------------------- ### 执行授权认证命令 Source: https://doc.catchadmin.vip/start/install 在项目根目录执行授权认证,需提供注册邮箱和生成的授权码。 ```shell php auth 邮箱 这里替换成生成的授权码 # 假设你的邮箱是 catch@pro.com,授权码是 123456 , 那么需要执行如下的命令 php auth catch@pro.com 123456 ``` -------------------------------- ### 项目打包 Source: https://doc.catchadmin.vip/start/client 针对不同操作系统进行打包,输出文件位于 dist 目录。 ```bash # 打包 windwos yarn build:win # 打包 MacOS yarn build:mac # 打包 linux yarn build:linux ``` -------------------------------- ### 使用 OSS 上传组件 Source: https://doc.catchadmin.vip/start/upgrade 在 Vue 模板中引入阿里 OSS 上传组件。 ```vue ``` -------------------------------- ### 修复依赖导入路径 Source: https://doc.catchadmin.vip/start/client 当遇到 package.json 加载错误时,修改 dependencies.vue 中的导入路径。 ```js // import packages from '@/../package.json' // 换成下面的 import packages from '@/../../../package.json' ``` -------------------------------- ### 启动开发环境 Source: https://doc.catchadmin.vip/start/client 启动开发服务器进行本地调试。 ```bash yarn dev ``` -------------------------------- ### 更新项目依赖与配置 Source: https://doc.catchadmin.vip/start/upgrade 拉取代码后更新依赖、发布配置并同步权限数据。 ```shell composer update --ignore-paltform-reqs php artisan vendor:publish --tag=catch-config --force php artisan catch:db:seed permissions ``` -------------------------------- ### Migrate System Tables Source: https://doc.catchadmin.vip/start/upgrade Run system migrations to apply database schema changes. This command should be executed after seeding the database. ```shell php artisan catch:migrate system ``` -------------------------------- ### 配置 API 路由分组 Source: https://doc.catchadmin.vip/start/app 在 routes/api.php 中按认证需求对路由进行分组管理。 ```php // 移动应用端 API 路由组织 - 按认证需求分组管理 Route::prefix('app')->group(function (){ // 公开接口:无需身份认证即可访问 Route::post('login', [AuthController::class, 'login']); // 私有接口:需要 JWT Token 认证才能访问 Route::middleware('auth:app')->group(function () { Route::post('logout', [AuthController::class, 'logout']); // 在此添加其他需要认证的 API 接口 }); }); ``` -------------------------------- ### 执行系统配置缓存命令 Source: https://doc.catchadmin.vip/start/upgrade 用于生成系统配置缓存的 Artisan 命令。 ```shell php artisan system:config:cache ``` -------------------------------- ### 安装依赖 Source: https://doc.catchadmin.vip/start/client 在项目根目录下执行以安装所有必要的依赖包。 ```bash yarn install ``` -------------------------------- ### 应用补丁文件 Source: https://doc.catchadmin.vip/start/develop 在 catch 分支上应用官方下载的补丁包。 ```shell # 首先切换到catch分支 git checkout catch # 应用补丁文件,--whitespace=nowarn参数可以忽略空白字符的警告 php artisan catch:upgrade xxx.zip(补丁文件) ``` -------------------------------- ### 初始化项目配置 Source: https://doc.catchadmin.vip/start/install 安装完成后,使用 artisan 命令初始化数据库结构和项目配置。 ```shell # 安装后台, 按照提示输入对应信息即可 php artisan catch:install ``` -------------------------------- ### 更新核心包版本 Source: https://doc.catchadmin.vip/start/upgrade 通过 Composer 更新 catchadmin/pro 核心包至指定版本。 ```shell composer require "catchadmin/pro:0.8.1" ``` -------------------------------- ### 使用断点调试函数 Source: https://doc.catchadmin.vip/start/upgrade 在开发过程中使用 catchadmin 提供的断点函数进行调试。 ```php // 使用 catchadmin 断点函数 dd_('断点调试') ``` -------------------------------- ### 实现认证控制器 Source: https://doc.catchadmin.vip/start/app 在 AuthController 中处理登录与退出逻辑,利用 UserService 进行身份验证。 ```php use App\Services\Auth\UserService; class AuthController extends Controller { /** * 登录 * * @param Request $request * @param UserService $service * @return JsonResponse */ public function login(Request $request, UserService $service): JsonResponse { // 系统封装了 UserService 用于处理用户登录 $user = $service->setAdapterType($request->get('type'))->auth($request->all()); if (! $user) { throw new UnauthorizedAccessException(); } return $this->success($user); } /** * @return JsonResponse */ public function logout(): JsonResponse { // 退出之后将 token 加入黑名单 $this->appGuard()->logout(true); return ApiResponse::success(); } } ``` -------------------------------- ### 配置接口地址 Source: https://doc.catchadmin.vip/start/client 在根目录的 .env 文件中设置后端接口地址,需与 Web Admin 配置保持一致。 ```text VITE_BASE_URL=这个跟你的web admin一样 ``` -------------------------------- ### 配置并安装前端依赖 Source: https://doc.catchadmin.vip/start/install 进入 web 目录配置 npm 镜像源并安装 Vue 项目依赖。 ```shell cd web # 配置 npm 镜像源(提升下载速度,如使用代理可忽略) yarn config set registry https://registry.npmmirror.com # 安装 Vue 项目 npm 依赖包 yarn install ``` -------------------------------- ### 配置前端环境变量 Source: https://doc.catchadmin.vip/start/install 在 web 目录下创建或修改 .env 文件以配置 API 地址和项目名称。 ```shell # 记住一定要加上 api/ 前缀 VITE_BASE_URL=http://127.0.0.1:8000/api/ # 项目名称 VITE_APP_NAME=xxx项目 ``` -------------------------------- ### CatchAdmin 一键打包命令 Source: https://doc.catchadmin.vip/start/deploy 使用 Artisan 命令自动打包项目。--no-check 参数可用于跳过前端类型检查。 ```shell php artisan catch:build ``` ```shell php artisan catch:build --no-check ``` -------------------------------- ### 配置后台登录路径 Source: https://doc.catchadmin.vip/start/upgrade 在前端 .env 文件中修改后台登录地址。 ```js VITE_LOGIN_PATH=/test/logins ``` -------------------------------- ### 配置微信认证路由 Source: https://doc.catchadmin.vip/start/upgrade 在 routes/web.php 中添加微信认证路由,并排除 CSRF 中间件验证。 ```php Route::any('wechat/auth', function () { return (new \Modules\Wechat\Support\Official\OfficialAccount())->serve(); })->withoutMiddleware([ \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class, ]); ``` -------------------------------- ### 执行权限迁移命令 Source: https://doc.catchadmin.vip/start/upgrade 在 Laravel 11 迁移后执行权限迁移。 ```shell php artisan catch:migrate permissions ``` -------------------------------- ### 更新核心包 Source: https://doc.catchadmin.vip/start/upgrade 使用 Composer 更新核心包。 ```shell composer update catchadmin/pro ``` -------------------------------- ### 更新补丁包 Source: https://doc.catchadmin.vip/start/upgrade 通过 Composer 安装补丁包并执行升级命令。 ```shell composer require "catchadmin/form:0.1.4" #执行更新命令 php artisan catch:upgrade xxxx.zip ``` ```shell composer update catchadmin/pro #执行更新命令 php artisan catch:upgrade xxxx.zip ``` -------------------------------- ### 创建升级专用分支 Source: https://doc.catchadmin.vip/start/develop 创建一个名为 catch 的分支,专门用于接收官方更新,不进行业务开发。 ```shell git checkout -b catch ``` -------------------------------- ### 安装版本升级补丁 Source: https://doc.catchadmin.vip/start/install 将下载的补丁包放置在根目录后,使用 artisan 命令执行升级。 ```shell php artisan catch:upgrade xxxx.zip ``` -------------------------------- ### 初始化 Git 仓库 Source: https://doc.catchadmin.vip/start/develop 项目开发前初始化 Git 仓库以跟踪代码变更。 ```shell git init ``` -------------------------------- ### 生产环境 Nginx 双域名配置 Source: https://doc.catchadmin.vip/start/deploy 前后端分离部署的 Nginx 服务器配置示例。 ```nginx server { listen 80; server_name admin.catchadmin.com; return 301 https://admin.catchadmin.com$request_uri; } server { listen 443 ssl http2; server_name admin.catchadmin.com; index.html index.php index.htm default.php default.htm default.html; ssl_certificate # pem文件的路径 ssl_certificate_key # key文件的路径 # HTTPS SSL 证书验证相关配置 ssl_session_timeout 5m; #缓存有效期 ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; # 开启 Gzip 压缩(提升传输速度) gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_http_version 1.1; gzip_comp_level 6; # 你原来是 9,压缩更强但更吃 CPU,这里建议 6 更均衡 gzip_vary on; gzip_proxied any; # 只压缩文本类/前端资源(别把图片视频之类塞进来) gzip_types text/plain text/css text/xml application/json application/javascript text/javascript application/xml image/svg+xml; gzip_disable "MSIE [1-6]\."; root /www/admin; location / { try_files $uri $uri/ /index.html =404; } } ``` ```nginx server { listen 80; server_name api.catchadmin.com; return 301 https://api.catchadmin.com$request_uri; } server { listen 443 ssl http2; server_name api.catchadmin.com; index index.html index.php index.htm default.php default.htm default.html; root /www/api/public; ssl_certificate /etc/nginx/acme/catchadmin.com/catchadmin.com.cer; # pem文件的路径 ssl_certificate_key /etc/nginx/acme/catchadmin.com/catchadmin.com.key; # key文件的路径 ssl_session_timeout 5m; #缓存有效期 ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; location / { if (!-e $request_filename) { rewrite ^(.*)$ /index.php?s=/$1 last; break; } } # PHP Laravel-FPM 支持配置 location ~ \.php$ { try_files $uri /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } ## Nginx 访问日志和错误日志配置(请根据实际需求配置) access_log; error_log; } ``` -------------------------------- ### Define API Method Documentation Source: https://doc.catchadmin.vip/start/api Document controller methods using annotations for URL parameters, request bodies, and response fields. ```php /** * 更新用户 * * @urlParam id int required 用户ID * * @bodyParam username string required 用户名 * @bodyParam password string 密码 * @bodyParam email string 邮箱 * @bodyParam mobile string 手机号 * @bodyParam department_id int 部门 * @bodyParam roles integer[] 角色 * @bodyParam jobs integer[] 职位 * * @responseField data bool 是否更新成功 * * @param $id * @param UserRequest $request * @return mixed */ public function update($id, UserRequest $request): mixed { // } ``` -------------------------------- ### 一键启动开发环境 Source: https://doc.catchadmin.vip/start/install 使用 composer 命令同时启动前后端开发环境,适用于 4.0.0+ 版本。 ```shell composer run dev ``` -------------------------------- ### 配置 Xdebug Source: https://doc.catchadmin.vip/start/debug 在 php.ini 文件中添加 Xdebug 扩展加载及模式配置。 ```php zend_extension=php_xdebug xdebug.mode=profile xdebug.start_with_request=yes ``` -------------------------------- ### 执行认证便捷脚本 Source: https://doc.catchadmin.vip/start/upgrade 通过命令行快速进行 auth 认证。 ```php php auth.php 邮箱 密码 ``` -------------------------------- ### 配置认证方式 Source: https://doc.catchadmin.vip/start/upgrade 修改配置文件以设置认证方式。 ```php // 找到 config/catch.php, 将 auth 改为 admin 即可 'auth' => 'admin', ``` -------------------------------- ### 执行正式环境安装命令 Source: https://doc.catchadmin.vip/start/upgrade 在正式环境中使用特定参数安装项目。 ```shell php artisan catch:install --prod ``` -------------------------------- ### CatchAdmin Professional Edition Directory Structure Source: https://doc.catchadmin.vip/start/overview Overview of the directory structure for the CatchAdmin Professional Edition, highlighting key directories for backend and frontend development. ```php ├─app ├─bootstrap ├─config(配置目录) ├─database(migration和seed存放目录) ├─lang(多语言目录) ├─public(运行目录 ├─modules(业务功能模块目录) | ├──User (后台用户管理 - 管理员账户和权限) | ├──Permissions (权限控制模块 - RBAC权限管理系统) | ├──Common (公共服务模块 - 基础功能和工具类) | ├──Pay (支付集成模块 - 多渠道支付解决方案) | ├──System (系统管理模块 - 系统配置和监控) | ├──Cms (内容管理系统 - 文章和页面管理) | ├──Shop (电商管理模块 - 商品、订单、库存管理) | ├──Develop (开发工具模块 - 代码生成器和开发辅助) | ├──Wechat (微信生态模块 - 公众号和小程序管理) | ├──Openapi (开放API模块 - 第三方系统集成接口) | ├──Domain (域名管理模块 - 多站点域名配置) | └──Member (会员系统模块 - 用户注册和会员管理) ├─web │ ├─src (前端目录) │ │ ├─assets | | ├─compoents (组件) | | ├─enum (枚举) | | ├─layout | | ├─router | | ├─store (pinia目录) | | ├─styles (样式目录) | | ├─support (助手方法) | | ├─types (类型目录) | | ├─views | | | App.vue | | | app.ts | | | env.d.ts │ | package.json │ | postcss.config.js │ | tailwind.config.js │ | tsconfig.json │ | tsconfig.node.json │ | vite.config.js (Vue项目配置) ├─routes ├─lang (多语言目录) ├─storage ├─tests │ .env-example(env配置示例) │ .gitattributes │ .gitignore │ .travis.yml │ composer.json │ .php-cs-fixer.dist.php │ phpunit.xml └─ artisan(命令行入口文件) ``` -------------------------------- ### 配置 Cursor MCP Source: https://doc.catchadmin.vip/start/develop 在 Cursor IDE 中配置 context7 MCP 以实现 AI 辅助开发。 ```json // cursor 示例 { "mcpServers": { "context7": { "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "YOUR_API_KEY" } } } } ``` -------------------------------- ### Create Storage Symbolic Link Source: https://doc.catchadmin.vip/start/bt-deploy This command creates a symbolic link for the storage directory, essential for file access. If you encounter an `Illuminate\Filesystem\symlink()` error, you may need to enable the `symlink` function in your PHP configuration. ```shell # 设置软链接 /www/server/php/82/bin/php artisan storage:link ``` -------------------------------- ### 合并升级变更 Source: https://doc.catchadmin.vip/start/develop 将 catch 分支的更新合并回开发分支。 ```shell # 切换回开发分支 git checkout master # 合并catch分支的变更 git merge catch ``` -------------------------------- ### 实现异常处理基类 Source: https://doc.catchadmin.vip/start/app 所有自定义异常类必须继承 ApiAppException 基类,以实现异常处理的统一化。 ```php abstract class ApiAppException extends HttpException { // public function __construct( string $message = '', Code $code = Code::FAILED ) { // 异常所有的 code 都使用枚举值,那么只需要维护 Code 枚举类就可以了 if ($this->code instanceof Enum) { $code = $this->code; $this->message = $this->code->message(); } parent::__construct( $this->statusCode(), $message ?: $this->message, null, [], $code->value ); } /** * @return int */ protected function statusCode(): int { return 500; } } ``` ```php use App\Enums\Code; class AuthenticationException extends ApiAppException { protected $code = Code::AUTH_EXCEPTION; } ``` -------------------------------- ### 执行项目打包命令 Source: https://doc.catchadmin.vip/start/upgrade 使用命令行将项目打包成 zip 包。 ```shell php think catch:build ``` -------------------------------- ### Nginx Configuration for Combined Frontend/Backend Deployment Source: https://doc.catchadmin.vip/start/deploy This Nginx configuration serves a Vue frontend from the root and routes API requests to a PHP backend. It handles SSL, Gzip compression, and static file serving for uploads. Ensure your SSL certificate and key paths are correctly set. ```nginx server { listen 80; server_name api.catchadmin.com; return 301 https://api.catchadmin.com$request_uri; } server { listen 443 ssl http2; server_name api.catchadmin.com; index index.html index.php index.htm default.php default.htm default.html; root /www/api/public; ssl_certificate # pem文件的路径 ssl_certificate_key # key文件的路径 ssl_session_timeout 5m; #缓存有效期 ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; # 开启 Gzip 压缩(提升传输速度) gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_http_version 1.1; gzip_comp_level 6; # 你原来是 9,压缩更强但更吃 CPU,这里建议 6 更均衡 gzip_vary on; gzip_proxied any; # 只压缩文本类/前端资源(别把图片视频之类塞进来) gzip_types text/plain text/css text/xml application/json application/javascript text/javascript application/xml image/svg+xml; gzip_disable "MSIE [1-6]"; # 因为接口都是以 api.catchadmin.com/api 开头,所以可以很好的使用 location # 如果访问 api.catchadmin.com/api 目录 则用 php 解释下 location /api { if (!-e $request_filename) { rewrite ^(.*)$ /index.php?s=/$1 last; break; } } # 根目录访问直接提供 Vue 前端静态文件 location / { root /www/api/public/admin; try_files $uri $uri/ /index.html; } # CatchAdmin 文件上传静态资源访问配置 location /uploads/ { alias /www/api/public/storage/uploads/; autoindex on; } # PHP Laravel-FPM 处理配置 location ~ \.php$ { try_files $uri /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } ``` -------------------------------- ### 用户认证服务核心逻辑 Source: https://doc.catchadmin.vip/start/app UserService 负责调用具体的登录适配器并处理用户 Token。 ```php /* @var Login $loginAdapter */ $loginAdapter = app($this->getLoginAdapter($this->type)); if ($res = $loginAdapter->auth($params)) { [$user, $token] = $res; $user->rememberToken($token); return $user->makeHidden([ 'password', 'from', 'creator_id' ]); } return false; ``` -------------------------------- ### Group API Controllers Source: https://doc.catchadmin.vip/start/api Use Doc annotations on controller classes to define documentation hierarchy. ```php /** * @group 公共模块 * * @subgroup 地区管理 * @subgroupDescription CatchAdmin 后台地区管理 */ class AreaController { // } ``` -------------------------------- ### Format PHP Code with Composer Pint Source: https://doc.catchadmin.vip/start/rules Command to format all eligible PHP files in the project according to the configured Laravel Pint rules. Ensures consistent code style across the project. ```shell composer pint ``` -------------------------------- ### 配置认证中间件 Source: https://doc.catchadmin.vip/start/app 实现 AuthMiddleware 以验证 JWT Token,并配置中间件别名及路由使用示例。 ```php class AuthMiddleware { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next, string $guard): Response { if (! $request->bearerToken()) { throw new TokenMissedException(); } $user = Auth::guard($guard)->user(); if (! $user) { throw new AuthenticationException(); } return $next($request); } } ``` ```php // 在 bootstrap/app.php 文件中注册中间件别名 ->withMiddleware(function (Middleware $middleware) { // $middleware->alias([ // 注册认证中间件别名,支持多种守卫:auth:app(移动端)、auth:web(后台)等 'auth' => AuthMiddleware::class ]); }) ``` ```php // 使用 auth:app 中间件,指定使用移动应用端的 JWT 认证守卫 Route::post('logout', [AuthController::class, 'logout'])->middleware('auth:app'); ``` -------------------------------- ### 修改 Vue 构建脚本 Source: https://doc.catchadmin.vip/start/deploy 通过修改 package.json 绕过 ts 类型检查错误。 ```json { "scripts": { "dev": "vite", "build": "vue-tsc --noEmit && vite build", // [!code --] "build": "vite build", // [!code ++] "preview": "vite preview" } } ``` -------------------------------- ### 安装 Xdebug 扩展 Source: https://doc.catchadmin.vip/start/debug 在 macOS 或 Linux 系统上通过 PECL 安装 Xdebug。 ```shell pecl install xdebug ``` -------------------------------- ### 实现多种登录方式 Source: https://doc.catchadmin.vip/start/app 包含密码登录、微信小程序登录及手机号快捷登录的实现逻辑。 ```php // app/Services/Auth/PasswordLogin.php // 自动识别登录账号类型:手机号格式则使用 mobile 字段,否则使用 username 字段 $field = preg_match('/^1[0123456789]\d{10}$/', $params['account']) ? 'mobile' : 'username'; // Auth 认证 $token = Auth::guard('app')->attempt([ $field => $params['account'], 'password' => $params['password'], ]); if ($token) { return [Auth::guard('app')->user(), $token]; } return false; ``` ```php // app/Services/Auth/WechatLogin.php try { // 通过微信小程序 code 换取 session_key 和 openid $response = $this->getMiniAppApplication()->getUtils()->codeToSession($params['code']); $user = $this->getAuthModel()->firstOrCreate([ 'miniapp_openid' => $response['openid'], ],[ 'username' => $params['username'], 'from' => 'miniprogram', 'miniapp_openid' => $response['openid'], 'avatar' => $this->storeAvatar(), 'mobile' => '', 'created_at' => time(), 'last_login_at' => time(), 'updated_at' => time(), ]); if (! $user) { return false; } return [$user, JWTAuth::fromUser($user)]; } catch (\Throwable $e) { throw new UnauthorizedAccessException(); } ``` ```php // app/Services/Auth/WechatByMobileLogin.php try { // 获取微信小程序用户的 openid $openid = $this->getMiniAppOpenId($params['code']); // 检查是否已存在该 openid 的用户记录 $user = $this->getAuthModel()->where('miniapp_openid', $openid)->first(); if ($user) { $user->username = $params['username']; $user->mobile = $this->getMiniAppUserMobile($params['phoneCode']); $user->avatar = $this->storeAvatar(); $user->last_login_at = time(); $user->updated_at = time(); $user->save(); } else { $user = $this->getAuthModel()->firstOrCreate([ 'mobile' => $this->getMiniAppUserMobile($params['phoneCode']), ], [ 'username' => $params['username'], 'from' => 'miniprogram', 'avatar' => $this->storeAvatar(), 'miniapp_openid' => $openid, 'created_at' => time(), 'last_login_at' => time(), 'updated_at' => time(), ]); } if (! $user) { return false; } return [$user, JWTAuth::fromUser($user)]; } catch (\Throwable $e) { throw new UnauthorizedAccessException(); } ``` -------------------------------- ### AI 查询提示词 Source: https://doc.catchadmin.vip/start/develop 用于引导 AI 通过 MCP 查询 catchadmin 文档的提示词。 ```text 请先通过 context7 mcp 查询 catchadmin 相关文档(这里可以是模型,可以其他功能) ``` -------------------------------- ### Seed System Database Source: https://doc.catchadmin.vip/start/upgrade Seed the system database with necessary data after pulling code changes. This command ensures the database is up-to-date with system configurations. ```shell php artisan catch:db:seed system ``` -------------------------------- ### 统一 API 响应处理 Source: https://doc.catchadmin.vip/start/app ApiResponse 类提供标准化的成功、错误及分页响应格式,确保客户端接收到一致的数据结构。 ```php /** * 移动应用端统一 API 响应处理类 * 确保所有接口返回一致的数据格式 */ class ApiResponse { /** * 成功响应 - 标准成功数据格式 */ public static function success(mixed $data = [], string $message = 'success', Code $code = Code::SUCCESS): JsonResponse { return response()->json([ 'code' => $code->value, 'message' => $message, 'data' => $data, ]); } /** * 错误响应 - 标准错误信息格式 */ public static function error(string $message = 'api error', int|Code $code = Code::FAILED): JsonResponse { return response()->json([ 'code' => $code instanceof Enum ? $code->value : $code, 'message' => $message, ]); } /** * 分页响应 - 列表数据分页格式 */ public static function paginate(LengthAwarePaginator $paginator, string $message = 'success', Code $code = Code::SUCCESS): JsonResponse { return response()->json([ 'code' => $code->value, 'message' => $message, 'data' => $paginator->items(), 'total' => $paginator->total(), 'limit' => $paginator->perPage(), 'page' => $paginator->currentPage(), ]); } } ```