### Installing Dependencies and Starting Documentation Site (Shell)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/api.md
These shell commands are used to set up and launch the generated API documentation site. After generating the documentation with `php artisan catch:api:doc`, `yarn install` is executed to install the necessary Vitepress dependencies. Subsequently, `yarn docs:dev` starts the documentation site locally, allowing developers to view the generated API documentation in a browser.
```Shell
yarn install
// 启动文档
yarn docs:dev
```
--------------------------------
### Installing CatchAdmin Modules via Artisan
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/module.md
This shell command initiates the module installation process in CatchAdmin. It prompts the user to select specific modules for installation, which then generates a 'module.json' file in 'storage/app' containing module-related information.
```shell
php artisan catch:module:install
```
--------------------------------
### Installing Permissions Module - CLI
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/permission.md
This command-line interface (CLI) command is used to install and enable the `permissions` module in the `catchadmin` framework. It's the first step to activate the permission system and dynamic menus.
```Bash
php artisan catch:module:install permissions
```
--------------------------------
### Running Authentication Setup Script in PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This PHP command executes a convenient authentication script, `auth.php`, which takes an email and password as arguments. This script is designed to simplify the setup or modification of authentication credentials.
```php
php auth.php 邮箱 密码
```
--------------------------------
### Installing Catch Admin in Production Environment (Shell)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This shell command executes the `catch:install` Artisan command with the `--prod` flag. This optimizes the project installation process for production environments, potentially skipping development tools and module management features.
```sh
php artisan catch:install --prod
```
--------------------------------
### Providing Module Information in CatchAdmin Installer
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/module.md
This PHP snippet from a module's 'Installer' class demonstrates how to provide essential metadata about the module. The 'info()' method returns an array containing details like title, name, path, keywords, description, and the main service provider, which is crucial for module discovery and management.
```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.
}
}
```
--------------------------------
### Starting Database Transaction (Traditional) - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/model.md
This code snippet shows the traditional way to start a database transaction using the `DB` facade.
```php
DB::beginTransaction();
```
--------------------------------
### Example URL for Dynamic Image Parameters
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/image.md
This snippet provides an example URL demonstrating how to access the dynamically processed image from the previous PHP route. It shows how to pass `width`, `height`, and `quality` parameters as query strings to manipulate the image on demand.
```shell
/image?width=100&height=50&quality=100
```
--------------------------------
### Generated Quick Search Query Example - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/model.md
This code demonstrates the dynamic query generated by the `quickSearch` method based on the `searchable` configuration and incoming request parameters.
```php
Model::select('*')
->where('status', $request->get('status'))
->whereLike('nickname', $request->get('nickname'))
->get();
```
--------------------------------
### Installing CatchAdmin Form Component - Shell
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This command installs the `catchadmin/form` component via Composer, which is a prerequisite for using the new CURD building components and the `` frontend component. It adds the necessary backend dependencies to your project.
```shell
composer require catchadmin/form
```
--------------------------------
### Example Module Configuration in modules.json (JSON)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/faq.md
This JSON snippet illustrates the structure of a module entry in `storage/app/modules.json`. It defines metadata for a module, including its title, name, path, description, service provider, version, and crucially, an `enable` flag to indicate if the module is active, which is relevant for route discovery.
```json
{
"title": "权限管理",
"name": "permissions",
"path": "permissions",
"keywords": "权限, 角色, 部门",
"description": "权限管理模块",
"provider": "\\Modules\\Permissions\\Providers\\PermissionsServiceProvider",
"version": "1.0.0",
"enable": true
}
```
--------------------------------
### Starting Database Transaction (Model Method) - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/model.md
This code snippet demonstrates the simplified approach to starting a database transaction directly from the model instance, along with other transaction operations.
```php
$this->beginTransaction();
```
--------------------------------
### Example Permission Identifier for Roles Index - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/permission.md
This example demonstrates a specific permission identifier for the `index` action of the `RolesController` within the `permissions` module. This format is used internally for permission checks.
```PHP
Modules\permissions\Http\Controller\RolesController@index
```
--------------------------------
### Implementing AliPay Payment Provider in PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/pay.md
This class `AliPay` extends the abstract `Pay` class, providing a concrete implementation for Alipay. It defines the `refund` method, specifies how to get the Alipay instance, wraps callback data into `AliPayNotifyData`, and sets the order number prefix to 'A'. It also lists various payment methods supported by the Alipay provider through magic methods.
```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';
}
}
```
--------------------------------
### Switching Image Disk in PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/image.md
This example shows how to specify a custom disk for reading an image using the `disk()` method. The image `avatars/example.jpg` is read from `custom_disk`, resized to 200px width, and output as PNG. Disk configurations are defined in `config/filesystem.php`.
```php
return Image::of('avatars/example.jpg')
->response()
->disk('custom_disk') // 从自定义磁盘读取图片
->width(200)
->png();
```
--------------------------------
### Starting Laravel Schedule Worker - Shell
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/async.md
This shell command is used to start the Laravel schedule worker, which is essential for processing scheduled jobs and asynchronous tasks in the background. It's explicitly noted that this command is intended for local development and testing environments only, and should not be used in a production setup.
```Shell
php artisan schedule:work
```
--------------------------------
### Defining Module Dependencies in CatchAdmin Installer
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/module.md
This PHP code snippet shows how to declare dependencies for a module within its 'Installer' class. By implementing the 'dependencies()' method and returning an array of module names (e.g., 'member'), it ensures that all required modules are installed concurrently.
```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'];
}
}
```
--------------------------------
### Configuring Composer with Recommended Packagist Mirror (Shell)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/faq.md
This command globally configures Composer to use the recommended `packagist.pages.dev` mirror for package downloads. It helps resolve dependency installation issues, especially with newly released Laravel versions, by providing a faster or more reliable mirror.
```shell
composer config -g repos.packagist composer https://packagist.pages.dev
```
--------------------------------
### Performing GET Requests in UniApp (TypeScript)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/uniapp/api.md
This snippet demonstrates how to execute a GET request using the `http` utility function. It requires a URL, specifies the 'GET' method, and allows for optional query parameters to be included in the request.
```TypeScript
import { http } from '@/utils/http'
return http({
url: `/someurl`,
method: 'GET',
query: { name: 'value' }
})
```
--------------------------------
### Configuring Composer with Huawei Cloud Packagist Mirror (Shell)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/faq.md
This command globally configures Composer to use the Huawei Cloud mirror for Packagist. It is currently recommended for its reliability and speed, helping to resolve dependency installation issues caused by slow mirror updates.
```shell
composer config -g repo.packagist composer https://repo.huaweicloud.com/repository/php/
```
--------------------------------
### Declaring Package Dependencies in CatchAdmin Module Installer
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/module.md
This PHP method within a module's 'Installer' class is used to declare external Composer package dependencies. By calling '$this->composer()->require('package/name')', the module can ensure that necessary third-party packages are installed when the module itself is installed.
```php
protected function requirePackages(): void
{
// TODO: Implement requirePackages() method.
$this->composer()->require('package/name')
}
```
--------------------------------
### Handling Permission Gate Middleware - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/permission.md
This PHP middleware, `PermissionGate`, controls access based on user permissions. It allows all `GET` requests by default and intercepts other requests if the authenticated user lacks the necessary permissions, throwing a `PermissionForbidden` exception.
```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);
}
}
```
--------------------------------
### Initiating WeChat Official Account Payment in PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/pay.md
This snippet demonstrates how to initiate a WeChat Official Account payment using the `PayFactory`. It requires a subject, amount, and the user's openid. This is a basic example and needs to be integrated with actual business logic for a complete payment flow.
```PHP
// 公众号支付
\Modules\Pay\Support\PayFactory::make(\Modules\Pay\Enums\Pay::WECHAT_PAY)
->mp([
'subject' => '公众号支付测试',
'amount' => 1,
'openid' => 'xxxxxxxxxxxxxxx'
]);
```
--------------------------------
### Example Excel Data Format for User Import
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/import.md
This snippet illustrates the expected column headers and data structure for the Excel file used in the user import process. It includes columns for ID, username, email, and password.
```PHP
id 昵称 邮箱 密码
1 test tests@admin.com 123456
2 tests test@admin.com 123456
```
--------------------------------
### Configuring Searchable Fields - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/model.md
This example shows how to configure the `searchable` property to define search fields and their corresponding operators (e.g., equality for 'status', 'like' for 'nickname').
```php
protected array $searchable = [
'status' => '==',
'nickname' => 'like'
]
```
--------------------------------
### Defining Openapi API Routes with Signature Middleware (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/openapi.md
This PHP code defines an API route group under the `/v1` prefix, applying the `CheckSignatureMiddleware` to enforce signature verification for all routes within this group. It includes a sample GET endpoint `/user` that returns a success response, demonstrating how to integrate the openapi module's security features into an application's routing.
```php
Route::prefix('v1')->middleware([
\Modules\Openapi\Middlewares\CheckSignatureMiddleware::class
])->group(function () {
Route::get('user', function (){
return \Modules\Openapi\Facade\OpenapiResponse::success([]);
});
});
```
--------------------------------
### Defining Laravel API Resource Routes for CMS and Shop Modules (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/faq.md
This PHP code demonstrates how to define API resource routes for `CategoryController` within `cms` and `shop` prefixes. While seemingly correct for modular routing, this setup leads to route naming conflicts when caching routes due to identical default resource names.
```php
// cms 分类路由
Route::prefix('cms')->group(function () {
Route::apiResource('category', CategoryController::class);
});
// shop 分类路由
Route::prefix('shop')->group(function () {
Route::apiResource('category', CategoryController::class);
});
```
--------------------------------
### Apifox Pre-request Script for Openapi Signature Generation (JavaScript)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/openapi.md
This JavaScript code is an Apifox (or Postman) pre-request script designed to dynamically generate and add the `app-key` and `signature` headers to API requests. It retrieves `app_key` and `app_secret` from environment variables, calculates an HMAC-SHA256 signature based on request parameters and a timestamp, and appends necessary headers and query parameters for both GET and URL-encoded POST requests.
```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') {
}
}
```
--------------------------------
### Using Creator Scope in Queries - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/model.md
This example demonstrates how to use the `scopeCreator` method to retrieve records associated with their creators. The table must contain a `creator_id` field for this scope to function.
```php
Model::select('*')->creator()->get();
```
--------------------------------
### Updating Authentication Guard Configuration in PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This PHP snippet shows how to update the authentication guard configuration in `config/catch.php` from its default to 'admin'. This is a breaking change required after removing the default authentication setup, ensuring proper authentication handling.
```php
'auth' => 'admin',
```
--------------------------------
### Getting Environment Variable Value (TypeScript)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/front/functions.md
This function retrieves the value of a specified environment variable. It takes the variable's key as a string and returns its corresponding value, which can be of any type. This is useful for configuring application behavior based on the deployment environment.
```TypeScript
env(key: string): any
```
```TypeScript
// 获取 API 基础 URL
const baseUrl = env('VITE_BASE_URL')
// 获取应用名称
const appName = env('VITE_APP_NAME')
```
--------------------------------
### Generating CatchAdmin API Documentation (Shell)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/api.md
This shell command is used to generate the API documentation for CatchAdmin projects. Executing `php artisan catch:api:doc` will create detailed interface documentation files in the `api-doc` directory at the project root, which are then used to build a Vitepress-based documentation site. This command simplifies the documentation generation process for module-based CatchAdmin backends.
```Shell
php artisan catch:api:doc
```
--------------------------------
### Documenting API Endpoint Parameters (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/api.md
This PHP snippet illustrates how to document a complex API endpoint method, specifically for updating a user. It uses `@urlParam` for path parameters, `@bodyParam` for request body parameters (including required fields and array types like `integer[]`), and `@responseField` to describe the expected response data. This comprehensive annotation set helps generate detailed API documentation for consumers.
```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
{
//
}
```
--------------------------------
### Defining API Grouping for Controllers (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/api.md
This PHP snippet demonstrates how to define API groups and subgroups for controllers using Doc annotations. The `@group` annotation specifies the top-level directory, `@subgroup` defines the second-level directory (corresponding to the controller), and `@subgroupDescription` provides a description for the subgroup. This helps organize API documentation into logical sections.
```PHP
/**
* @group 公共模块
*
* @subgroup 地区管理
* @subgroupDescription CatchAdmin 后台地区管理
*/
class AreaController
{
//
}
```
--------------------------------
### Getting File Extension (TypeScript)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/front/functions.md
This function extracts the file extension from a given filename. It returns the extension including the leading dot (e.g., '.pdf'), useful for file type validation or categorization.
```TypeScript
getFileExt(filename: string): string
```
```TypeScript
const ext = getFileExt('document.pdf') // 结果: ".pdf"
```
--------------------------------
### Getting Filename from Path (TypeScript)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/front/functions.md
This function extracts the base filename from a given file path. It returns only the filename without the directory path, useful for displaying file names or processing individual files.
```TypeScript
getFilename(filename: string): string
```
```TypeScript
const name = getFilename('/path/to/document.pdf') // 结果: "document.pdf"
```
--------------------------------
### Implementing configPath in CatchModuleServiceProvider (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/config.md
This snippet demonstrates how to customize the configuration path for a module by implementing the `configPath` method within a `CatchModuleServiceProvider`. This allows modules to define their own independent configuration directories, overriding the default system behavior.
```PHP
namespace Modules\Test\Providers;\n\nuse Catch\CatchAdmin;\nuse Catch\Providers\CatchModuleServiceProvider;\n\nclass TestServiceProvider extends CatchModuleServiceProvider\n{\n public function confitPath(): string\n {\n return config_path;\n }\n}
```
--------------------------------
### Creating Storage Symlink - PHP Artisan
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This PHP Artisan command creates a symbolic link from `public/storage` to `storage/app/public`. This allows uploaded files in the `storage` directory to be directly accessible via HTTP, resolving issues where files could not be accessed directly.
```shell
php artisan storage:link
```
--------------------------------
### Pushing Asynchronous Task to Queue - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/async.md
This PHP snippet demonstrates the straightforward process of initiating an asynchronous task. It instantiates the `AsyncTask` class and then calls its `push()` method, which dispatches the task to the background queue for later execution, allowing the current request to complete without delay.
```PHP
$async = new AsyncTask()
$async->push()
```
--------------------------------
### Retrieving All Permissions for a User - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/permission.md
This PHP code demonstrates how to retrieve all permissions associated with a user. It assumes `$user` is an instance of `Model\Roles` and uses the `withPermissions()` method to eager load and access the user's permissions.
```PHP
/*@var Model\Roles $user*/
$user->withPermissions()->permissions;
```
--------------------------------
### Handling Dynamic Image Parameters with PHP Route
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/image.md
This PHP route demonstrates dynamic image processing by accepting `width`, `height`, and `quality` parameters from the request. It retrieves an image from a specified disk and applies the requested transformations before outputting it as a PNG. This allows for on-the-fly image manipulation.
```php
Route::get('image', function () {
return Image::of('avatars/5fi5kxDVbd7NGhzY4b0NphYMa5Tg5lWDnBRjqhxU.jpg')
->response()
->disk('some_your_disk')
->width(request()->get('width'))
->height(request()->get('height'))
->quality(request()->get('quality'))
->png();
})
```
--------------------------------
### Accessing Global Configuration (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/config.md
This snippet shows the standard Laravel-like method for accessing a global configuration value. It is presented to contrast with the module-specific configuration access method, highlighting that module configurations require a different approach.
```PHP
config('one')
```
--------------------------------
### Retrieving All Permissions for a Role - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/permission.md
This PHP code snippet illustrates how to fetch all permissions assigned to a specific role. It assumes `$role` is an instance of `Model\Roles` and calls the `getPermissions()` method on it.
```PHP
/*@var Model\Roles $role*/
$role->getPermissions()
```
--------------------------------
### Accessing Module-Specific Configuration (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/config.md
This snippet illustrates the correct way to access a module-specific configuration value. It requires prefixing the configuration key with the module's name (e.g., 'permissions'), followed by the configuration file name and the specific key within that file.
```PHP
config('permissions.one.some_key')
```
--------------------------------
### Seeding System Database - PHP Artisan
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This command executes the `system` database seeder for the CatchAdmin project. It is required after pulling code updates to ensure the database is populated with the latest system-related data, especially for new features like interface monitoring.
```shell
php artisan catch:db:seed system
```
--------------------------------
### Executing Project Build Command in Shell
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This shell command executes the `catch:build` Artisan command using PHP's `think` utility. Its purpose is to package the entire project into a zip archive, facilitating deployment or distribution.
```shell
php think catch:build
```
--------------------------------
### Registering Webhook Platform in CatchAdmin (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/webhook.md
This PHP method `getWebhookPlatform()` demonstrates how new webhook platforms (like Feishu) are registered and resolved within the CatchAdmin system. It uses a hardcoded array to map platform constants to their respective class names, ensuring the correct platform instance is configured and returned.
```PHP
protected function getWebhookPlatform(): WebhookInterface
{
$platform = [
Webhooks::FEISHU => Feishu::class, // 飞书
][$this->webhook->platform] ?? null;
if (! $platform) {
throw new FailedException('The platform dont support now.');
}
return app($platform)->config($this->webhook->webhook, $this->webhook->secret);
}
```
--------------------------------
### Implementing Quick Search - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/model.md
This method enables quick searching by leveraging the model's `searchable` property in conjunction with request parameters. It dynamically generates query conditions based on the `searchable` configuration.
```php
public function quickSearch(array $params = [])
```
--------------------------------
### Defining Asynchronous Task Table Structure - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/async.md
This PHP snippet defines the database schema for the 'async_task' table using Laravel's Schema builder. It includes fields for storing task details like the associated class name, parameters, start time, status, execution duration, error messages, results, and retry count, along with standard timestamps.
```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();
});
```
--------------------------------
### Implementing Global Routing Guard - TypeScript
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/front/side-route.md
Implements a global navigation guard using `router.beforeEach` to manage route access based on user authentication and permissions. It checks for an authentication token, redirects logged-in users from the login page, fetches user information and dynamic permissions if not already loaded, and then dynamically adds routes to the router based on the retrieved permissions, ensuring proper access control and a smooth user experience.
```TypeScript
const guard = (router: Router) => {
// white list
const whiteList: string[] = [WhiteListPage.LOGIN_PATH, WhiteListPage.NOT_FOUND_PATH]
router.beforeEach(async (to, from, next) => {
// set page title
setPageTitle(to.meta.title as unknown as string)
// page start
progress.start()
// 获取用户的 token
const authToken = getAuthToken()
// 如果 token 存在
if (authToken) {
// 如果进入 /login 页面,重定向到首页
if (to.path === WhiteListPage.LOGIN_PATH) {
next({ path: '/' })
} else {
const userStore = useUserStore()
// 获取用户ID
if (userStore.getId) {
next()
} else {
try {
// 阻塞获取用户信息
// ⚠️ 用户信息已经包含了该用户所有可用权限,在 `permissions` 里
await userStore.getUserInfo()
// 如果后端没有返回 permissions,前台则只使用静态路由
if (userStore.getPermissions !== undefined) {
// 挂载路由(实际是从后端获取用户的权限)
const permissionStore = usePermissionsStore()
// 动态路由挂载,这里是主要实现动态路由菜单的地方
const asyncRoutes = permissionStore.getAsyncMenusFrom(toRaw(userStore.getPermissions))
// 在这里使用 addRoute 动态挂在路由
asyncRoutes.forEach((route: Menu) => {
router.addRoute(route as unknown as RouteRecordRaw)
})
}
next({ ...to, replace: true })
} catch (e) {
removeAuthToken()
next({ path: `${WhiteListPage.LOGIN_PATH}?redirect=/${to.path}` })
}
}
}
progress.done()
} else {
// 如果不在白名单
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next({ path: WhiteListPage.LOGIN_PATH })
}
progress.done()
}
})
router.afterEach(() => {
progress.done()
})
}
export default guard
```
--------------------------------
### Implementing Abstract Payment Base Class in PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/pay.md
This abstract class `Pay` provides a foundational structure for payment implementations. It includes methods for creating unique order numbers (both for payments and refunds), handling dynamic method calls for payment actions, processing payment notifications, and loading payment configurations. Subclasses must implement abstract methods like `instance()`, `getNotifyData()`, `orderNoPrefix()`, and `platform()` to provide specific payment gateway logic.
```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));
}
}
```
--------------------------------
### Configuring Composer with Tencent Cloud Packagist Mirror (Shell)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/faq.md
This command globally sets Composer to use the Tencent Cloud mirror for Packagist. This can improve download speeds and reliability for users within regions served by Tencent Cloud, addressing slow mirror updates.
```shell
composer config -g repos.packagist composer https://mirrors.tencent.com/composer/
```
--------------------------------
### Configuring catchadmin Framework Settings (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/config.md
This PHP configuration file (`config/catch.php`) defines core settings for the `catchadmin` framework. It includes parameters for super administrator ID, module management (root directory, namespace, default modules, default directories, driver, routes, autoload), JSON response handling, database SQL logging, authentication model and guard, API routing prefix and middlewares, and the path for frontend Vue views. These settings allow for extensive customization of the framework's behavior and structure.
```php
return [
/*
|--------------------------------------------------------------------------
| catch-admin 超级管理员
|--------------------------------------------------------------------------
|
| 可以设置超级管理的用户 ID
| 支持数组
*/
'super_admin' => 1,
/*
|--------------------------------------------------------------------------
| catch-admin 请求允许
|--------------------------------------------------------------------------
|
| 默认允许 GET 请求通过 RBAC 权限
*/
'request_allowed' => true,
/*
|--------------------------------------------------------------------------
| catch-admin 模块设置
|--------------------------------------------------------------------------
|
| 设置模块根目录
| 设置模块的根命名空间
| 设置模块默认生成的文件夹
*/
'module' => [
'root' => 'modules',
'namespace' => 'Modules',
/**
* 默认启动的模块
*/
'default' => ['develop', 'user', 'common'],
'default_dirs' => [
'Http'.DIRECTORY_SEPARATOR,
'Http'.DIRECTORY_SEPARATOR.'Requests'.DIRECTORY_SEPARATOR,
'Http'.DIRECTORY_SEPARATOR.'Controllers'.DIRECTORY_SEPARATOR,
'Models'.DIRECTORY_SEPARATOR,
],
// 模块存储驱动
// 默认使用文件驱动
'driver' => [
// currently, catchadmin support file and database
// the default is driver
'default' => 'file',
// use database driver
'table_name' => 'admin_modules',
],
/**
* 模块路由集合
*/
'routes' => [],
/**
* 模块是否自动加载
*
* 如果设置成 true,模块会自动全部加载
*/
'autoload' => env('CATCH_MODULE_AUTOLOAD', false),
],
/*
|--------------------------------------------------------------------------
| catch-admin 响应
|--------------------------------------------------------------------------
*/
'response' => [
// JSON 响应, 保证响应数据都是 json
'always_json' => \Catch\Middleware\JsonResponseMiddleware::class,
// 响应监听者
// 监听[RequestHandled]事件
'request_handled_listener' => \Catch\Listeners\RequestHandledListener::class,
],
/*
|--------------------------------------------------------------------------
| 数据库 SQL 日志
|--------------------------------------------------------------------------
*/
'listen_db_log' => env('APP_DEBUG', true),
/*
|--------------------------------------------------------------------------
| 管理员授权认证模型
|--------------------------------------------------------------------------
*/
'auth_model' => \Modules\User\Models\User::class,
/*
|--------------------------------------------------------------------------
| 管理员授权 Guard
|--------------------------------------------------------------------------
*/
'auth' => 'admin',
/*
|--------------------------------------------------------------------------
| 路由配置
|--------------------------------------------------------------------------
*/
'route' => [
'prefix' => 'api',
'middlewares' => [
\Catch\Middleware\AuthMiddleware::class,
\Catch\Middleware\JsonResponseMiddleware::class,
],
],
/*
|--------------------------------------------------------------------------
| 前端 Vue 视图文件夹路径
|
| 如果不设置,将不会生成相关的 Vue 文件
|--------------------------------------------------------------------------
*/
'views_path' => base_path('web'.DIRECTORY_SEPARATOR.'src'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR),
/*
|--------------------------------------------------------------------------
| 开启系统接口日志分析
|
| 接口日志依赖 Redis,提高性能
|--------------------------------------------------------------------------
*/
'system_api_log' => env('CATCH_SYSTEM_API_LOG', false),
];
```
--------------------------------
### Defining Permission Identifier Format - Text
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/permission.md
This snippet illustrates the standardized format for permission identifiers within the `catchadmin` modular system. It combines the module, controller, and action names to create a unique permission string.
```Text
module@controller@action
```
--------------------------------
### Integrating Alibaba OSS Upload Component in Vue
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This Vue snippet demonstrates the usage of the `` component. It's a new component introduced for handling file uploads directly to Alibaba Cloud OSS, simplifying integration of cloud storage functionalities.
```vue
```
--------------------------------
### Implementing Asynchronous Task Interface - PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/async.md
This PHP class provides a basic implementation of the `AsyncTaskInterface`. The `push()` method stores the task's class name and parameters into the `async_task` table, while the `run()` method serves as a placeholder for the actual business logic that will be executed when the task is processed, receiving the parameters pushed earlier.
```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 参数
// 自定义实现任务
}
}
```
--------------------------------
### Defining CatchAdmin Module Service Provider
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/module.md
This PHP snippet illustrates the basic structure of a module's service provider in CatchAdmin. Extending 'CatchModuleServiceProvider', it defines the 'moduleName' method, which is crucial for the framework to identify and load the module's components, including routes, commands, and configurations.
```php
namespace Modules\Test\Providers;
use Catch\CatchAdmin;
use Catch\Providers\CatchModuleServiceProvider;
class TestServiceProvider extends CatchModuleServiceProvider
{
public function moduleName(): string|array
{
return 'common';
}
}
```
--------------------------------
### Implementing Module Middlewares in CatchAdmin Service Provider
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/module.md
This PHP snippet shows how to define global middlewares for all modules by implementing the 'middlewares()' method in the 'TestServiceProvider'. It's important to note that middlewares defined here apply broadly, and for module-specific routing, they should be set directly in the module's routes.
```php
class TestServiceProvider extends CatchModuleServiceProvider
{
protected function middlewares(): array
{
return [];
}
}
```
--------------------------------
### Defining Application Response Codes with PHP Enum
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/app.md
This PHP `enum` defines standard response codes for the application, such as `SUCCESS`, `FAILED`, and various `TOKEN` related states. It implements the `Enum` interface and provides `message()` and `equal()` methods to retrieve human-readable messages for each code and compare enum values, respectively. This centralizes error code management.
```PHP
/**
* 枚举项目的返回码
*/
enum Code:int implements Enum
{
case SUCCESS = 10000;
case FAILED = 10001;
case LOGIN_FAILED = 10002;
case AUTH_EXCEPTION = 10003;
case TOKEN_EXPIRED = 10004;
case TOKEN_INVALID = 10005;
case TOKEN_BLACKLIST = 10006;
case TOKEN_MISSED = 10007;
/**
* @return string
*/
public function message(): string
{
return match ($this) {
self::SUCCESS => 'success',
self::FAILED => 'failed',
self::LOGIN_FAILED => '登录失败',
self::AUTH_EXCEPTION => '认证失败',
self::TOKEN_EXPIRED => 'token 过期',
self::TOKEN_INVALID => 'token 无效',
self::TOKEN_BLACKLIST => 'token 黑名单',
self::TOKEN_MISSED => 'token 丢失',
};
}
/**
* @param mixed $value
* @return bool
*/
public function equal(mixed $value): bool
{
return $this->value === $value;
}
}
```
--------------------------------
### Admin Panel Layout File Structure (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/front/layout.md
This PHP-like snippet illustrates the directory structure of the admin panel's layout files, primarily located under `web/src/layout`. It details the organization of core layout components such as header, menu, content, and sider, providing a clear overview of the frontend system's architectural design and component reusability.
```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
```
--------------------------------
### Defining Permissions Pinia Store - TypeScript
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/front/side-route.md
Defines the `Permissions` interface and the `usePermissionsStore` Pinia store, which centrally manages all permission and menu-related state. The store's state includes `menus`, `asyncMenus` (for dynamically generated menus), `permissions` (raw permission data), and `menuPathMap`, all designed to be reactive, allowing the sidebar and other UI components to automatically update when permission data changes.
```TypeScript
interface Permissions {
menus: Menu[] // 菜单
asyncMenus: Menu[] // 动态菜单
permissions: Permission[] // 权限
menuPathMap: Map // menu 和 path 的 MAP 数据
}
export const usePermissionsStore = defineStore('PermissionsStore', {
// state 里面定义的几个数据都是响应式的
state: (): Permissions => {
return {
menus: [],
asyncMenus: [],
permissions: [],
menuPathMap: new Map(),
}
},
}
```
--------------------------------
### Exporting Module Menus via CatchAdmin Artisan
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/module.md
This shell command is used to export dynamic menu information associated with a specific module. The optional '' parameter allows specifying the target table (defaulting to 'permissions'), primarily useful when packaging modules for distribution.
```shell
php artisan catch:export:menu
```
--------------------------------
### Migrating System Database - PHP Artisan
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/upgrade.md
This command runs migrations specifically for the `system` module in CatchAdmin. It's essential to execute this after code updates to apply any new database schema changes or modifications related to system functionalities, such as interface monitoring.
```shell
php artisan catch:migrate system
```
--------------------------------
### Configuring Global Exception Handling in Laravel PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/app.md
This PHP snippet shows how to configure global exception rendering within a Laravel application's `bootstrap/app.php` file. It specifically renders `ApiAppException` instances as standardized `ApiResponse::error` JSON responses and provides a fallback for other system exceptions, ensuring all API errors are returned consistently.
```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());
}
});
})
```
--------------------------------
### Implementing Base Application Exception with PHP Abstract Class
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/app.md
This abstract PHP class serves as the base for all custom application exceptions. It extends `HttpException` and automatically sets the exception message and code based on the `Code` enum, promoting consistent error reporting across the application. Custom exceptions should inherit from this class.
```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;
}
}
```
--------------------------------
### Defining Specific Authentication Exception in PHP
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/start/app.md
This PHP class demonstrates how to define a specific application exception, `AuthenticationException`, by extending `ApiAppException`. It simply sets the `protected $code` property to a value from the `Code` enum, allowing the base class to handle the message and status code automatically.
```PHP
use AppEnumsCode;
class AuthenticationException extends ApiAppException
{
protected $code = Code::AUTH_EXCEPTION;
}
```
--------------------------------
### Scheduling Asynchronous Task Command (PHP)
Source: https://github.com/catch-admin/pro-docs/blob/master/docs/server/import.md
This snippet, located in `app/Console/Kernel.php`, schedules the `async:task` command to run every minute. This command is responsible for processing the dispatched asynchronous import tasks, ensuring they are executed in the background.
```PHP
protected function schedule(Schedule $schedule): void
{
$schedule->command('async:task')->everyMinute();
}
```