### Installing Project Dependencies with pnpm Source: https://doc.catchadmin.vip/uniapp/start This command installs all necessary project dependencies using pnpm. It should be executed from the project's root directory after downloading and extracting the UniApp version. ```shell pnpm i ``` -------------------------------- ### Installing Vitepress Dependencies and Starting Documentation Server (Shell) Source: https://doc.catchadmin.vip/start/api After generating API documentation, these commands are used to prepare and serve the documentation site. `yarn install` installs the necessary Vitepress dependencies, and `yarn docs:dev` starts a local development server to view the generated API documentation. ```Shell yarn install // 启动文档 yarn docs:dev ``` -------------------------------- ### Installing pnpm Globally Source: https://doc.catchadmin.vip/uniapp/start This command installs pnpm globally on your system. pnpm is the recommended package manager for this project, ensuring efficient dependency management and avoiding common issues found with other package managers. ```shell npm install -g pnpm ``` -------------------------------- ### Starting UniApp Development Mode for Mini Programs Source: https://doc.catchadmin.vip/uniapp/start This command initiates the development server for UniApp, specifically targeting mini-programs. After execution, developers can import the compiled directory (`dist/dev/mp-weixin`) into the WeChat developer tools to preview and debug the application. ```shell pnpm dev:mp ``` -------------------------------- ### UniApp Project Directory Structure Source: https://doc.catchadmin.vip/uniapp/start This snippet outlines the standard directory structure of the UniApp project. It details the organization of API interfaces, environment variables, hooks, pages, static resources, state management, and utility functions, providing a clear overview for navigation and development. ```shell ├── api # 存放接口目录 │   └── login.ts # 登录接口 ├── env ## 存放环境变量文件 │   ├── .env │   ├── .env.development │   ├── .env.production │   └── .env.test ├── env.d.ts # 存放环境变量类型定义文件 ├── favicon.ico ├── hooks # 存放钩子目录 │   ├── .gitkeep │   └── useNavbarWeixin.ts # 使用微信导航 ├── index.html ├── interceptors # 存放拦截器目录 │   ├── index.ts # 拦截器 │   ├── request.ts # 请求拦截器 │   └── route.ts # 路由拦截器 ├── layouts # 存放布局目录 │   ├── default.vue │   └── demo.vue ├── pages # 存放页面目录 │   ├── index # 首页 │   │   └── index.vue │   ├── login # 登录页面 │   │   └── index.vue │   └── my # 个人中心 │   └── index.vue ├── pages-sub # 存放子页面目录 │   └── demo.vue ├── shell │   └── postinstall.js ├── static # 存放静态资源目录 │   ├── logo.png │   ├── logo.svg │   └── tabbar │   ├── example.png │   ├── exampleHL.png │   ├── home.png │   ├── homeHL.png │   ├── personal.png │   └── personalHL.png ├── store # 存放 store 目录 │   ├── count.ts # │   ├── index.ts # │   └── user.ts # ├── utils # 工具目录 │   ├── http.ts # http 客户端 │   ├── index.ts # 工具函数 │   └── toPath.ts # 路径跳转 ├── tsconfig.json ├── types │   └── auto-import.d.ts ├── typing.ts ├── commitlint.config.cjs ├── uni.scss ├── uno.config.ts # unocss 配置 ├── unocss.css # unocss 样式 ├── pages.config.ts # 存放页面配置文件 ├── project.config.json ├── project.private.config.json ├── App.vue # 主入口文件 ├── main.js # 主入口文件 ├── manifest.config.ts ├── package.json ├── .editorconfig ├── .eslintignore ├── .eslintrc-auto-import.json ├── .eslintrc.cjs ├── .gitignore ├── .npmrc ├── .prettierignore ├── .prettierrc.cjs ├── .stylelintignore ├── .stylelintrc.cjs ├── LICENSE ├── README.md └── vite.config.ts # vite 配置 ``` -------------------------------- ### Building UniApp for WeChat Mini Program Production Source: https://doc.catchadmin.vip/uniapp/start This command compiles the UniApp project into a production-ready build specifically for the WeChat Mini Program platform. The output is located in `dist\build\mp-weixin`, ready for upload via the WeChat developer tools. ```shell pnpm build:mp-weixin ``` -------------------------------- ### Installing CatchAdmin Modules via Artisan (Shell) Source: https://doc.catchadmin.vip/server/module This command initiates the installation process for CatchAdmin modules, prompting the user to select modules to install. After execution, `storage/app/module.json` is generated, containing module information. ```shell php artisan catch:module:install ``` -------------------------------- ### Configuring Environment Variables for UniApp Source: https://doc.catchadmin.vip/uniapp/start This snippet shows the essential environment variables to configure in the `env/.env` file. `VITE_APP_TITLE` sets the application's display name, and `VITE_SERVER_BASEURL` specifies the backend API endpoint for network requests. These settings are crucial for application functionality and branding. ```typescript VITE_APP_TITLE = // 应用名称 VITE_SERVER_BASEURL = // 请求的接口地址 ``` -------------------------------- ### Providing Module Information in CatchAdmin Installer (PHP) Source: https://doc.catchadmin.vip/server/module This PHP snippet from a module's `Installer` class shows the implementation of the `info` method. This method returns an array containing metadata about the module, such as its title, name, path, keywords, description, and the main service provider class, essential for module registration and display. ```php namespace Modules\Permissions; use Catch\Support\Module\Installer as ModuleInstaller; class Installer extends ModuleInstaller { protected function info(): array { // TODO: Implement info() method. return [ 'title' => '权限管理', 'name' => 'permissions', 'path' => 'permissions', 'keywords' => '权限, 角色, 部门', 'description' => '权限管理模块', 'provider' => PermissionsServiceProvider::class ]; } protected function requirePackages(): void { // TODO: Implement requirePackages() method. } protected function removePackages(): void { // TODO: Implement removePackages() method. } } ``` -------------------------------- ### Example URL for Dynamic Image Parameters Shell Source: https://doc.catchadmin.vip/server/image This shell snippet provides an example URL demonstrating how to access the dynamically processed image endpoint. It shows the use of `width`, `height`, and `quality` query parameters to control the image output. ```shell /image?width=100&height=50&quality=100 ``` -------------------------------- ### Declaring Module Dependencies in CatchAdmin Installer (PHP) Source: https://doc.catchadmin.vip/server/module This PHP code snippet from a module's `Installer` class demonstrates how to declare dependencies on other modules using the `dependencies` method. In this example, the 'Shop' module depends on the 'member' module, ensuring both are installed together. ```php namespace Modules\Shop; use Catch\Support\Module\Installer as ModuleInstaller; use Modules\Shop\Providers\ShopServiceProvider; class Installer extends ModuleInstaller { // 添加模块依赖 protected function dependencies(): array { return ['member']; } } ``` -------------------------------- ### Installing CatchAdmin Form Component - Shell Source: https://doc.catchadmin.vip/start/upgrade This command installs the `catchadmin/form` component via Composer, which provides a fast CURD (Create, Read, Update, Delete) building component. It's a prerequisite for using the new `` frontend component. ```shell composer require catchadmin/form ``` -------------------------------- ### Installing CatchAdmin in Production Environment (Shell) Source: https://doc.catchadmin.vip/start/upgrade This command-line snippet shows how to install CatchAdmin specifically for a production environment. The --prod flag ensures that the installation process is optimized for production, potentially omitting development tools and modules. ```shell php artisan catch:install --prod ``` -------------------------------- ### Example Module Configuration (JSON) Source: https://doc.catchadmin.vip/faq This JSON snippet illustrates the structure of a module configuration file (`storage/app/modules.json`). The `enable` field, when set to `true`, indicates that the module is active, which is crucial for its routes and functionalities to be recognized by the application. ```json { "title": "权限管理", "name": "permissions", "path": "permissions", "keywords": "权限, 角色, 部门", "description": "权限管理模块", "provider": "\\Modules\\Permissions\\Providers\\PermissionsServiceProvider", "version": "1.0.0", "enable": true } ``` -------------------------------- ### Installing JWT Authentication Package (Composer) Source: https://doc.catchadmin.vip/start/app This command installs the `tymon/jwt-auth` package via Composer, which provides JWT (JSON Web Token) based authentication capabilities for Laravel applications. This step is necessary for CatchAdmin versions older than 3.2.0 to enable JWT authentication. ```shell composer require "tymon/jwt-auth" ``` -------------------------------- ### Performing GET Requests in UniApp (TypeScript) Source: https://doc.catchadmin.vip/uniapp/api This snippet demonstrates how to make a GET request using the `http` utility. It specifies the URL and includes query parameters for data retrieval. ```TypeScript import { http } from '@/utils/http' return http({ url: `/someurl`, method: 'GET', query: { name: 'value' } }) ``` -------------------------------- ### Example Excel Data Format for Import Source: https://doc.catchadmin.vip/server/import This snippet illustrates the expected column headers and sample data rows for an Excel file intended for user import. It serves as a reference for structuring the input data. ```PHP // excel 格式如下 id 昵称 邮箱 密码 1 test tests@admin.com 123456 2 tests test@admin.com 123456 ``` -------------------------------- ### Declaring Composer Package Dependencies in CatchAdmin Installer (PHP) Source: https://doc.catchadmin.vip/server/module This PHP code snippet from a module's `Installer` class illustrates how to implement the `requirePackages` method. This method uses the `composer()` helper to declare external Composer package dependencies that the module requires, ensuring they are installed during the module installation process. ```php protected function requirePackages(): void { // TODO: Implement requirePackages() method. $this->composer()->require('package/name'); } ``` -------------------------------- ### Performing Basic HTTP Requests with Http Object - TypeScript Source: https://doc.catchadmin.vip/front/request This snippet demonstrates how to use the `Http` object for common HTTP methods: GET, POST, PUT, and DELETE. It imports the `Http` object from `/admin/support/http` and shows the basic signature for each request type, including parameters for GET and data for POST/PUT. ```typescript import Http from '/admin/support/http' // GET 请求 http.get(path: string, params: object = {}) // POST 请求 http.post(path: string, data: object = {}) // PUT 请求 http.put(path: string, data: object = {}) // DELETE 请求 http.delete(path: string) ``` -------------------------------- ### Configuring Composer with Packagist Pages Mirror (Shell) Source: https://doc.catchadmin.vip/faq This command configures Composer to use `packagist.pages.dev` as the global Packagist mirror. This is recommended for faster dependency downloads, especially when facing issues with Laravel 11 installation due to slow mirror updates. ```shell composer config -g repos.packagist composer https://packagist.pages.dev ``` -------------------------------- ### Permission Mark Format Examples (JavaScript) Source: https://doc.catchadmin.vip/front/permissions These examples illustrate the expected formats for permission marks used by the `v-action` directive and backend systems. Permissions can be structured as `module.controller.action` or `module@controller@action`, providing a clear hierarchical identifier for specific operations within the application. ```javascript module.controller.action or module@controller@action ``` -------------------------------- ### Starting Laravel Scheduler for Asynchronous Tasks Source: https://doc.catchadmin.vip/server/async This shell command starts the Laravel scheduler in `schedule:work` mode. This command is used for local testing to continuously run scheduled tasks, including asynchronous tasks, and should not be used in a production environment. ```shell php artisan schedule:work ``` -------------------------------- ### Applying Image Watermark with Custom Options (PHP) Source: https://doc.catchadmin.vip/server/image This example illustrates how to apply a watermark image to a source image, controlling its position (bottom-right), offset, and transparency. It also shows how to apply additional image processing (brightness, contrast) before saving the watermarked image to a specified disk with custom quality settings. ```PHP // 图片的相对地址,默认使用 uploads 磁盘 $path = 'avatars/5fi5kxDVbd7NGhzY4b0NphYMa5Tg5lWDnBRjqhxU.jpg'; // 水印图片,绝对路径 $waterImage = \Illuminate\Support\Facades\Storage::disk('uploads')->path('water.jpg'); / 创建带水印的图片并保存 Image::of($sourcePath) ->watermark($watermarkPath) // 设置水印图片 ->bottomRight() // 放置在右下角 ->offset(20, 20) // 距离边缘20像素 ->opacity(40) // 设置40%的透明度 ->saving(function ($watermark, $image) { // 在添加水印前对原图进行额外处理 $image->brightness(5)->contrast(10); }) ->save( 'products/product-display-watermarked.jpg', // 保存路径 'public', // 保存到public磁盘 ['quality' => 85] // 设置85%的图片质量 ); ``` -------------------------------- ### Implementing WeChat Mini-Program Login in Laravel Source: https://doc.catchadmin.vip/start/app This PHP snippet from `app/Services/Auth/WechatLogin.php` manages WeChat mini-program user login. It uses the provided `code` to get session information, then finds or creates a user based on the `miniapp_openid`. Upon successful authentication, it returns the user object and a JWT token; otherwise, it throws an `UnauthorizedAccessException`. ```php // app/Services/Auth/WechatLogin.php try { $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(); } ``` -------------------------------- ### Eager Loading Relations in List Queries with setBeforeGetList (PHP) Source: https://doc.catchadmin.vip/server/model This example shows how `setBeforeGetList` can be utilized to eager load relationships using the `with()` method. Eager loading helps optimize queries by fetching related data in a single query, preventing the N+1 query problem when iterating over a list of models and accessing their relationships. ```PHP $model->setBeforeGetList(function ($query) { return $query->with('some_relations'); })->getList(); ``` -------------------------------- ### Example Permission Identifier for Roles List - PHP Context Source: https://doc.catchadmin.vip/server/permission This example illustrates a specific permission identifier for accessing the roles list within the permissions module. It follows the `module@controller@action` format, pointing to the `index` action of the `RolesController` in the `permissions` module. ```php Modules\permissions\Http\Controller\RolesController@index ``` -------------------------------- ### Saving Text Overlay Image to Laravel Storage Disk (PHP) Source: https://doc.catchadmin.vip/server/image This example illustrates how to add text to an image and then save the resulting image directly to a specified Laravel storage disk, such as 'public', providing flexibility in file management. ```PHP Image::of('path/to/image.jpg') ->text('你好,世界!') ->fontsize(24) ->color('#FF0000') ->save('output.jpg', 'public'); ``` -------------------------------- ### Implementing Table Search with Catch-Table (Vue.js) Source: https://doc.catchadmin.vip/front/catch-table This example extends the basic `catch-table` usage by adding search functionality. It introduces the `:search-form` prop, which defines input fields for 'username' and 'email', allowing users to filter table data. The `api` prop remains 'users'. ```javascript ``` -------------------------------- ### Customizing List Queries with setBeforeGetList (PHP) Source: https://doc.catchadmin.vip/server/model This example demonstrates how to use the `setBeforeGetList` method to apply custom sorting to a model's list query. By passing a closure, you can modify the query builder (e.g., `orderByDesc('sort')`) before the list data is fetched, allowing for flexible and dynamic ordering of results. ```PHP $model->setBeforeGetList(function ($query) { return $query->orderByDesc('sort'); })->getList(); ``` -------------------------------- ### Integrating Openapi Signature Check Middleware in PHP Source: https://doc.catchadmin.vip/server/openapi This PHP snippet demonstrates how to integrate the `CheckSignatureMiddleware` into an API route group. It defines a `v1` API prefix and applies the middleware to ensure all requests within this group are properly signed. A simple GET route `/user` is included to show a successful response using `OpenapiResponse::success([])` after signature verification. ```php Route::prefix('v1')->middleware([ \Modules\Openapi\Middlewares\CheckSignatureMiddleware::class ])->group(function () { Route::get('user', function (){ return \Modules\Openapi\Facade\OpenapiResponse::success([]); }); }); ``` -------------------------------- ### Defining Module Name in CatchAdmin Service Provider (PHP) Source: https://doc.catchadmin.vip/server/module This PHP code snippet shows the `TestServiceProvider` extending `CatchModuleServiceProvider`. The `moduleName` method is overridden to return the module's name, which is 'common' in this example, indicating how a module identifies itself within the CatchAdmin framework. ```php namespace Modules\Test\Providers; use Catch\CatchAdmin; use Catch\Providers\CatchModuleServiceProvider; class TestServiceProvider extends CatchModuleServiceProvider { public function moduleName(): string|array { return 'common'; } } ``` -------------------------------- ### Apifox Pre-request Script for Openapi Signature Generation in JavaScript Source: https://doc.catchadmin.vip/server/openapi This JavaScript snippet is an Apifox pre-request script designed to automate the generation of API signatures. It retrieves `appKey` and `appSecret` from environment variables, calculates an HMAC-SHA256 signature based on request parameters and a timestamp, and then adds the `app-key` and `signature` headers to the request. It handles both GET and URL-encoded POST requests, ensuring proper authentication before the request is sent. ```javascript const appKey = pm.environment.get('app_key') const appSecret = pm.environment.get('app_secret') console.log(appSecret, appKey) function createSign(params) { const keys = Object.keys(params).sort() const signStr = keys.map((key) => `${key}=${params[key]}`).join('&') return CryptoJS.HmacSHA256(signStr, appSecret).toString() } let params = {} params['timestamp'] = Math.floor(Date.now() / 1000) if (pm.request.method == 'GET') { queryString = pm.request.url.getQueryString() if (queryString) { pm.request.url .getQueryString() .split('&') .forEach((item) => { items = item.split('=') params[items[0]] = items[1] }) } const signature = createSign(params) pm.request.headers.add({ key: 'app-key', value: appKey }) pm.request.headers.add({ key: 'signature', value: signature }) let query = '' for (let key in params) { query += key + '=' + params[key] + '&' } pm.request.url.query = query } else { if (pm.request.body.mode == 'urlencoded') { pm.request.body.urlencoded.each((item) => { params[item.key] = item.value }) const signature = createSign(params) pm.request.headers.add({ key: 'app-key', value: appKey }) pm.request.headers.add({ key: 'signature', value: signature }) pm.request.body.urlencoded.add({ disabled: false, key: 'timestamp', value: params.timestamp }) } if (pm.request.body.mode == 'formdata') { } } ``` -------------------------------- ### Adding Webhook Event Options for Frontend in CatchAdmin PHP Source: https://doc.catchadmin.vip/server/webhook This PHP class `WebhookEvents` implements the `OptionInterface` to provide a structured list of available webhook event options for frontend interfaces. The `get()` method returns an array of associative arrays, each containing a `label` for display and a `value` corresponding to the event constant defined in the `Webhooks` model, enabling dynamic selection of event types. ```php class WebhookEvents implements OptionInterface { public function get(): array { return [ [ 'label' => '异常事件', 'value' => 'exception', ], [ 'label' => '其他事件', 'value' => 'other_event', ] ]; } } ``` -------------------------------- ### Example Usage of v-action Directive in Template (HTML) Source: https://doc.catchadmin.vip/front/permissions This HTML template snippet demonstrates how to use the `v-action` directive within a Vue component. The `` element is controlled by the `user@user@store` permission mark. If the current user does not have this specific permission, the button will not be rendered or will be hidden, enforcing frontend access control. ```html ``` -------------------------------- ### Defining Data Recovery Route for Catch-Table Trash Bin (PHP) Source: https://doc.catchadmin.vip/front/catch-table To support data recovery from the trash bin, a dedicated route needs to be defined in the backend. This PHP snippet shows an example using Laravel's `Route::put` to create a `restore` endpoint for the `UserController`, allowing specific user records to be restored by their ID. ```php // 回收站恢复 Route::put('users/restore/{id}', [UserController::class, 'restore']); ``` -------------------------------- ### Setting Request Header with Http Object - TypeScript Source: https://doc.catchadmin.vip/front/request This example demonstrates how to add a custom header to an HTTP request using `Http.setHeader()`. It takes a key-value pair for the header and is chained with a GET request. ```typescript Http.setHeader(key:string, value:string).get() ``` -------------------------------- ### Using Authentication Convenience Script (PHP) Source: https://doc.catchadmin.vip/start/upgrade This PHP command-line snippet illustrates how to use the auth.php script to quickly set up authentication credentials. It takes an email and password as arguments, simplifying the process of creating or updating user authentication. ```php php auth.php 邮箱 密码 ``` -------------------------------- ### Setting Base URL for Http Requests - TypeScript Source: https://doc.catchadmin.vip/front/request This snippet illustrates how to set a custom base URL for HTTP requests using `Http.setBaseUrl()`. This allows subsequent requests to be made relative to the specified base URL, followed by a GET request example. ```typescript Http.setBaseUrl('https://api.com').get() ``` -------------------------------- ### Generating CatchAdmin API Documentation (Shell) Source: https://doc.catchadmin.vip/start/api This shell command is used to generate the professional version of API documentation for CatchAdmin projects. Executing this command creates the documentation files in the `api-doc` directory at the project root, which can then be served as a Vitepress site. ```Shell php artisan catch:api:doc ``` -------------------------------- ### Executing Project Build Command in CatchAdmin (Shell) Source: https://doc.catchadmin.vip/start/upgrade This command-line snippet demonstrates how to use the php think catch:build command to automatically package the project into a zip file. This utility simplifies deployment by creating a ready-to-distribute archive. ```shell php think catch:build ``` -------------------------------- ### Grouping Controllers for API Documentation (PHP) Source: https://doc.catchadmin.vip/start/api This PHP snippet demonstrates how to group controllers using `@group`, `@subgroup`, and `@subgroupDescription` annotations. These annotations define the primary and secondary directory structures for the generated API documentation, organizing controllers and providing descriptive labels. ```PHP /** * @group 公共模块 * * @subgroup 地区管理 * @subgroupDescription CatchAdmin 后台地区管理 */ class AreaController { // } ``` -------------------------------- ### Configuring Composer with Tencent Cloud Mirror (Shell) Source: https://doc.catchadmin.vip/faq This command sets the global Composer Packagist mirror to Tencent Cloud's repository. It provides an alternative mirror for downloading PHP dependencies, which can be beneficial for users in regions with better connectivity to Tencent Cloud services. ```shell composer config -g repos.packagist composer https://mirrors.tencent.com/composer/ ``` -------------------------------- ### Implementing AliPay Payment in PHP Source: https://doc.catchadmin.vip/server/pay This class `AliPay` extends the abstract `Pay` class, providing a concrete implementation for Alipay. It defines methods for handling refunds (`refund`), creating the Alipay provider instance (`instance`), wrapping callback data into `AliPayNotifyData` (`getNotifyData`), and specifying the order number prefix ('A'). It also includes PHPDoc comments for various Alipay payment methods (web, h5, app, mini, pos, scan, transfer). ```PHP /** * @method ResponseInterface|Rocket web(array $order) 网页支付 * @method ResponseInterface|Rocket h5(array $order) H5 支付 * @method ResponseInterface|Rocket app(array $order) APP 支付 * @method Rocket|Collection mini(array $order) 小程序支付 * @method Rocket|Collection pos(array $order) 刷卡支付 * @method Rocket|Collection scan(array $order) 扫码支付 * @method Rocket|Collection transfer(array $order) 账户转账 */ class AliPay extends Pay { public function refund(array $params): mixed { $refundData = $this->createRefundData([ 'refund_amount' => $params['amount'], ]); } /** * @return \Yansongda\Pay\Provider\Alipay * * @throws \Yansongda\Artful\Exception\ContainerException */ protected function instance(): mixed { PayProvider::config(config('pay.alipay')); return PayProvider::alipay(); } /** * 包装回调数据 */ protected function getNotifyData(array $data): NotifyData { return new AliPayNotifyData($data); } protected function orderNoPrefix(): string { return 'A'; } } ``` -------------------------------- ### Configuring Composer with Huawei Cloud Mirror (Shell) Source: https://doc.catchadmin.vip/faq This command configures Composer to use Huawei Cloud's PHP repository as the global Packagist mirror. This is currently suggested as a reliable alternative for dependency management, potentially offering better performance or stability. ```shell composer config -g repo.packagist composer https://repo.huaweicloud.com/repository/php/ ``` -------------------------------- ### Switching Image Disk with CatchAdmin PHP Source: https://doc.catchadmin.vip/server/image This code shows how to specify a custom disk for reading an image using the `disk()` method. The image 'avatars/example.jpg' is loaded from 'custom_disk', resized to 200px width, and returned as a PNG. Disk configurations are defined in `config/filesystem.php`. ```php return Image::of('avatars/example.jpg') ->response() ->disk('custom_disk') // 从自定义磁盘读取图片 ->width(200) ->png(); ``` -------------------------------- ### Defining API Endpoint Parameters and Responses (PHP) Source: https://doc.catchadmin.vip/start/api This PHP snippet illustrates how to document an API endpoint's parameters and expected responses using various annotations. It covers `@urlParam` for path parameters, `@bodyParam` for request body parameters (including types and optionality), and `@responseField` for documenting the structure of the API response. ```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 { // } ``` -------------------------------- ### Setting Request Timeout with Http Object - TypeScript Source: https://doc.catchadmin.vip/front/request This code shows how to configure a timeout for an HTTP request using the `Http.timeout()` method. It sets the timeout to 5 units (likely seconds) before initiating a GET request. ```typescript Http.timeout(5).get() ``` -------------------------------- ### Creating Storage Symlink - PHP Artisan Source: https://doc.catchadmin.vip/start/upgrade This PHP Artisan command creates a symbolic link from `public/storage` to `storage/app/public`. This allows web servers to directly serve files uploaded to the `storage` directory, making them publicly accessible. ```php php artisan storage:link ``` -------------------------------- ### Configuring Image Driver and Read Disk in .env (PHP) Source: https://doc.catchadmin.vip/server/image This snippet shows how to configure the default image processing driver (GD or Imagick) and the default storage disk for reading images within the .env file. These settings control the core behavior of the local image processing features. ```PHP # 默认处理图片的驱动 GD 扩展 CATCH_IMAGE_DRIVER=gd # 默认从 uploads 磁盘读取 CATCH_IMAGE_READ_FROM=uploads ``` -------------------------------- ### CatchAdmin PermissionGate Middleware Implementation - PHP Source: https://doc.catchadmin.vip/server/permission This PHP middleware, `PermissionGate`, is responsible for enforcing access control on incoming requests. It automatically allows GET requests but verifies the authenticated user's permissions for other methods, throwing a `PermissionForbidden` exception if access is denied. ```php class PermissionGate { public function handle(Request $request, \Closure $next) { // get 请求全部通过 if ($request->isMethod('get')) { return $next($request); } /* @var User $user */ $user = $request->user(getGuardName()); // 没有权限则被拦截 if (! $user->can()) { throw new PermissionForbidden(); } return $next($request); } } ``` -------------------------------- ### Publishing JWT Configuration File Source: https://doc.catchadmin.vip/start/app This Artisan command publishes the default configuration file for the `tymon/jwt-auth` package. This allows developers to customize JWT settings, such as token expiration, algorithms, and secret keys, by modifying the `config/jwt.php` file. ```shell php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" ``` -------------------------------- ### Configuring Image Processing in config/catch.php (PHP) Source: https://doc.catchadmin.vip/server/image This configuration block, to be added or updated in `config/catch.php`, defines the image processing settings. It specifies the driver (defaulting to GD if not set in .env) and the default disk for reading source images, ensuring consistent behavior across the application. ```PHP return [ /* |-------------------------------------------------------------------------- | 图片处理配置 | | 控制图片处理的核心参数和默认行为 |-------------------------------------------------------------------------- */ 'image' => [ // 图片处理驱动,从环境变量获取,默认使用GD库 'driver' => env('CATCH_IMAGE_DRIVER', 'gd'), // 图片处理附加选项,可根据需要扩展 'options' => [ // 在此添加自定义选项 ], /** * 默认读取图片的存储磁盘 * 此设置决定了图片处理功能默认从哪个存储磁盘读取源图片 */ 'read_from' => env('CATCH_IMAGE_READ_FROM', 'uploads'), ], ] ``` -------------------------------- ### Seeding System Database - PHP Artisan Source: https://doc.catchadmin.vip/start/upgrade This PHP Artisan command runs database seeders specifically for the 'system' module. It's used to populate the database with initial data, often required after pulling new code, especially for features like interface monitoring. ```php php artisan catch:db:seed system ``` -------------------------------- ### Exporting Module Menus via Artisan (Shell) Source: https://doc.catchadmin.vip/server/module This shell command is used to export menu information for a specified module, optionally to a specific table. It generates a `seed` file, which is particularly useful when packaging modules for distribution or sharing with others. ```shell php artisan catch:export:menu ``` -------------------------------- ### Handling File Uploads in UniApp (TypeScript) Source: https://doc.catchadmin.vip/uniapp/api This snippet shows how to perform a file upload using the `uniFileUpload` utility. It requires the file path, a name for the file, and allows for additional form data. ```TypeScript import { uniFileUpload } from '@/utils/http' return uniFileUpload({ url: `/someurl`, method: 'POST', filePath: filePath, // 文件地址 name: 'avatar', // 文件名称,这里叫 avatar formData: { // form 表单数据 ...params, type } }) ``` -------------------------------- ### Creating/Updating Data with useCreate Composable - TypeScript Source: https://doc.catchadmin.vip/front/request This code demonstrates the `useCreate` composable for handling both data creation and updates. It destructures form-related properties and conditionally calls `useShow` if `props.primary` exists (for updates). It also shows how to integrate with a `close` callback to emit a 'close' event. ```typescript const { formData, form, loading, submitForm, close } = useCreate(props.api, props.primary) // 更新的 ID if (props.primary) { useShow(props.api, props.primary, formData) } // 关闭弹窗 const emit = defineEmits(['close']) close(() => emit('close')) ``` -------------------------------- ### Adding New Data with Catch-Table Slot (Vue.js) Source: https://doc.catchadmin.vip/front/catch-table This example shows how to enable data addition functionality in `catch-table` using a `dialog` slot. It integrates a `Create` component (e.g., `create.vue`) into the slot, which is responsible for handling the form for new entries or updates. The `Create` component automatically receives `primary` (for updates) and `api` props for submission. ```javascript ``` -------------------------------- ### Joining Tables in List Queries with setBeforeGetList (PHP) Source: https://doc.catchadmin.vip/server/model This snippet illustrates using `setBeforeGetList` to perform a `join` operation within the list query. This allows you to combine data from multiple tables before retrieving the list, enabling more complex data retrieval scenarios where related information is needed. ```PHP $model->setBeforeGetList(function ($query) { return $query->join('some_table'....); })->getList(); ``` -------------------------------- ### Abstract Base Payment Class in PHP Source: https://doc.catchadmin.vip/server/pay This abstract class `Pay` implements `PayInterface` and provides common payment logic. It handles order number generation (`createOrderNo`, `createRefundOrderNo`), dispatches events for payment processing (`__call`) and notifications (`notify`), and defines abstract methods for specific payment instance creation (`instance`), callback data wrapping (`getNotifyData`), order number prefixing (`orderNoPrefix`), and platform identification (`platform`). It also includes a method to load payment configurations. ```PHP abstract class Pay implements PayInterface { /** * 支付实例 */ abstract protected function instance(): mixed; /** * 使用代理方法支付 * * @return mixed * * @throws RandomException */ public function __call($name, $params) { $params = array_merge(['action' => $name], ...$params); $payEvent = new PayEvent($this->createTradeData($params)); $params = Event::dispatch($payEvent); return $this->instance()->{$name}($params[0]); } /** * 回调 * * @throws ContainerException * @throws InvalidParamsException */ public function notify(): mixed { $notifyData = $this->instance()->callback()->toArray(); $notify = $this->getNotifyData($notifyData); try { Event::dispatch(new PayNotifyEvent($notify)); } catch (\Throwable $e) { // 失败如何处理 } finally { return $this->instance()->success(); } } /** * 获取回调数据 */ abstract protected function getNotifyData(array $data): NotifyData; /** * 订单号前缀 */ abstract protected function orderNoPrefix(): string; /** * @return PayPlatform */ abstract protected function platform(): PayPlatform; /** * 创建订单号 * * @throws RandomException */ protected function createOrderNo(): string { $prefix = $this->orderNoPrefix(); return $prefix.date('YmdHis').random_int(1000000, 9999999).Str::random(10); } /** * 创建退款订单号,退款订单号加个 R 字符 * * @throws RandomException */ public function createRefundOrderNo(): string { return 'R'.$this->createOrderNo(); } /** * @return array|string[] * * @throws RandomException */ protected function createTradeData(array $params): array { $params['order_no'] = $this->createOrderNo(); $params['platform'] = $this->platform(); return $params; } /** * 加载支付配置 * * @throws ContainerException|DdException */ protected function loadPayConfig(string $key): void { PayProvider::config(PayConfig::get($key)); } } ``` -------------------------------- ### Creating `async_task` Table Schema in PHP Source: https://doc.catchadmin.vip/server/async This PHP snippet defines the database schema for the `async_task` table using Laravel's Schema builder. It includes fields for task name, parameters, start time, status, time taken, error messages, results, retry count, and standard timestamps (created_at, updated_at, deleted_at). This table is crucial for storing and managing asynchronous task details. ```php Schema::create('async_task', function (Blueprint $table) { $table->id(); $table->string('task')->comment('task任务对应的 class 名称'); $table->string('params')->default('')->comment('任务所需参数'); $table->integer('start_at')->default(0)->comment('开始时间'); $table->tinyInteger('status')->default(1)->comment('状态:un_start=1,running=2,finished=3,error=4'); $table->integer('time_taken')->default(0)->comment('运行耗时'); $table->string('error')->default('')->comment('执行结果错误'); $table->string('result')->default('')->comment('执行结果'); $table->string('retry')->default(0)->comment('重试次数'); $table->createdAt(); $table->updatedAt(); $table->deletedAt(); }); ``` -------------------------------- ### Layout Directory Structure - PHP Source: https://doc.catchadmin.vip/front/layout This snippet outlines the directory structure for the layout files located under `web/src/layout`. It details the organization of various components such as header, menu, content, and sider, which collectively form the backend page layout. ```php ├─components │ ├─header (头部组件) │ │ ├─index.vue | | ├─lang.vue (多语言组件) | | ├─logo.vue (logo 组件) | | ├─menuSearch.vue (菜单搜索组件) | | ├─notification.vue (通知组件) | | ├─profile.vue (个人组件) | | ├─theme.vue (主题组件/暗黑模式) | ├─ Menu(头部组件) │ │ ├─index.vue | | ├─item.vue (菜单 item 组件) | | ├─mask.vue (mask 组件) | | ├─menus.vue (菜单组件) | | │ └─content.vue 主题内容 │ └─sider.vue 侧边栏 ├─index.vue ``` -------------------------------- ### Adding Basic Text Overlay to Image (PHP) Source: https://doc.catchadmin.vip/server/image This snippet demonstrates the fundamental process of adding text to an image. It covers setting the text content, font size, color, horizontal and vertical alignment, and an offset, before saving the modified image. ```PHP use Catch\Support\Image\Image; // 在图片上添加简单文字 Image::of('events/conference.jpg') ->text('2023年技术峰会') // 设置文字内容 ->fontsize(28) // 设置字体大小 ->color('#FFFFFF') // 设置白色文字 ->alignCenter() // 水平居中 ->valignBottom() // 垂直靠底部 ->offset(0, 30) // 距底部30像素 ->save('events/conference-titled.jpg'); ``` -------------------------------- ### Configuring Tree Search Component in Catch-Table (Vue.js/TypeScript) Source: https://doc.catchadmin.vip/front/catch-table This snippet demonstrates how to integrate a 'tree' type search component within `catch-table`. It uses Vue's `ref` for reactive data and `onMounted` to fetch category data asynchronously via an HTTP GET request. The `search` array defines the tree component with `options` bound to the reactive `categories` data and `props` for value and label mapping. ```typescript // 首先在 setup 中设置 search 相关组件 // 在 catch table 种设置 search 即可 ``` -------------------------------- ### Batch Updating Records in CatchAdmin Model (PHP) Source: https://doc.catchadmin.vip/server/model This snippet provides an example of using the `batchUpdate` method to efficiently update multiple records. It takes a field name for the condition, an array of condition values, and an associative array of data where keys are fields and values are arrays of corresponding update values. It's important that the number of condition values matches the number of data values for each field. This method does not trigger model events. ```PHP $model = new SomeModel(); $model->batchUpdate('id', [1,2,3], ['name' =>['小明', '小隋', '小书'], 'age' => [12, 12, 13]]); ``` -------------------------------- ### Implementing `AsyncTaskInterface` in PHP Source: https://doc.catchadmin.vip/server/async This PHP class provides a basic implementation of the `AsyncTaskInterface`. The `push()` method stores the current task class and parameters in the `AsyncTask` model, effectively adding it to the task queue. The `run()` method is where the actual business logic for the asynchronous task should be implemented, receiving parameters pushed during the `push()` call. ```php use Modules\System\Models\AsyncTask; class AsyncTask implements AsyncTaskInterface { // push 方法将当前任务推送到任务队列 public function push(): mixed { return app(AsyncTask::class) ->storeBy([ 'task' => get_called_class(), 'params' => '', // 参数需要自定义实现 ]); } // run 方法 任务具体业务线,它接受传进来的参数 public function run(array $params): mixed { // params 就是 push 进去的 params 参数 // 自定义实现任务 } } ```