### Project Setup with create-vue Source: https://router.vuejs.org/zh/guide This command demonstrates how to create a new Vue.js project with Vite and includes an option to integrate Vue Router. This is a convenient way to start a new project with the necessary setup for Vue Router. ```bash npm create vue@latest ``` ```bash yarn create vue ``` ```bash pnpm create vue ``` -------------------------------- ### Vue 渲染函数:使用内置组件 (JS - setup) Source: https://cn.vuejs.org/guide/extras/render-function.html 在 Vue 渲染函数的 `setup` 函数中导入并使用内置组件,如 ``。需要从 'vue' 模块显式导入这些组件才能在渲染函数中使用。 ```javascript import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue' export default { setup () { return () => h(Transition, { mode: 'out-in' }, /* ... */) } } ``` -------------------------------- ### 在选项式 API 中使用组合式函数 Source: https://cn.vuejs.org/guide/reusability/composables.html 演示了如何在 Vue 的选项式 API 中利用 `setup()` 函数调用组合式函数。组合式函数返回的绑定值需要在此 `setup()` 函数中返回,以便在组件实例(包括模板和 `this`)中可用。 ```javascript import { useMouse } from './mouse.js' import { useFetch } from './fetch.js' export default { setup() { const { x, y } = useMouse() const { data, error } = useFetch('...') return { x, y, data, error } }, mounted() { // setup() 暴露的属性可以在通过 `this` 访问到 console.log(this.x) } // ...其他选项 } ``` -------------------------------- ### Vue 渲染函数:渲染插槽 (JS - setup) Source: https://cn.vuejs.org/guide/extras/render-function.html 在 Vue 渲染函数的 `setup` 函数中访问和渲染插槽。`slots.default()` 用于渲染默认插槽,`slots.footer()` 用于渲染具名插槽,并可以传递 props。插槽函数返回 VNodes 数组。 ```javascript export default { props: ['message'], setup(props, { slots }) { return () => [ // 默认插槽: //
h('div', slots.default()), // 具名插槽: //
h( 'div', slots.footer({ text: props.message }) ) ] } } ``` -------------------------------- ### Install Backend Composer Dependencies on Server Source: https://context7_llms When deploying the Laravel backend, it's recommended to install dependencies on the server using `composer install` instead of uploading the `vendor` directory. This ensures compatibility with the server environment and reduces upload size. ```shell composer install ``` -------------------------------- ### 在 ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://context7_llms Installs project dependencies using the pnpm package manager. Ensure you have pnpm installed globally before running this command. This is a crucial step after downloading the project to ensure all required libraries are available. ```shell pnpm i ``` -------------------------------- ### Example AsyncTask Implementation (PHP) Source: https://context7_llms Provides an example implementation of the `AsyncTaskInterface`. The `push` method stores the task and its parameters in the `async_task` table, while the `run` method contains the custom logic for the task. This serves as a template for creating your own asynchronous operations. ```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 参数 // 自定义实现任务 } } ``` -------------------------------- ### Example of Exporting Menu Data for Permissions Module Source: https://context7_llms An example demonstrating the command to export menu data specifically for the 'permissions' module, which is useful during the module packaging and distribution phase. ```shell php artisan catch:export:menu permissions ``` -------------------------------- ### 声明 Vue 渲染函数 (JavaScript) Source: https://cn.vuejs.org/guide/extras/render-function.html 展示了如何在 `setup()` 钩子中返回一个渲染函数,该函数使用 `h` 函数创建 VNode。渲染函数可以访问 props 和响应式状态,并可以直接返回字符串、单个 VNode 或 VNode 数组。 ```javascript import { ref, h } from 'vue' export default { props: { /* ... */ }, setup(props) { const count = ref(1) // 返回渲染函数 return () => h('div', props.msg + count.value) } } ``` ```javascript export default { setup() { return () => 'hello world!' } } ``` ```javascript import { h } from 'vue' export default { setup() { // 使用数组返回多个根节点 return () => [ h('div'), h('div'), h('div') ] } } ``` -------------------------------- ### Vue JSX:渲染插槽 (setup) Source: https://cn.vuejs.org/guide/extras/render-function.html 在 JSX 中渲染插槽。默认插槽通过 `slots.default()` 渲染,具名插槽如 `slots.footer()` 也可以传递 props。这种方式允许在 JSX 模板中直接使用插槽内容。 ```jsx // 默认插槽
{slots.default()}
// 具名插槽
{slots.footer({ text: props.message })}
``` -------------------------------- ### Install CatchAdmin Module Source: https://context7_llms Installs a CatchAdmin module using the Artisan command-line tool. This command provides an interactive prompt to select modules for installation. ```shell php artisan catch:module:install ``` -------------------------------- ### Frontend Project Entry Point Source: https://context7_llms This snippet shows the main entry point for the frontend project, located in `main.ts`. It initializes the CatchAdmin application and starts the project by calling the bootstrap method. ```javascript import '@/styles/index.scss' import CatchAdmin from '@/support/catchAdmin' // 首先引入的是 catchadmin 对象 const admin = new CatchAdmin() // 启动项目 admin.bootstrap() ``` -------------------------------- ### Start the Scheduler for Local Testing (PHP) Source: https://context7_llms Starts the Artisan scheduler to process pending asynchronous tasks. This command is intended for local testing environments only and should not be used in production. It allows you to observe the execution of your asynchronous tasks directly. ```shell php artisan schedule:work ``` -------------------------------- ### 函数式组件 (JavaScript) Source: https://cn.vuejs.org/guide/extras/render-function.html 展示了一个简单的函数式组件,它直接声明为一个函数,无需 `setup` 或 `render` 选项。这种组件没有实例状态,非常简洁。 ```javascript function Hello() { return 'hello world!' } ``` -------------------------------- ### CatchAdmin Module Installer Implementation Source: https://context7_llms Defines the basic structure for a CatchAdmin module installer, providing metadata like title, name, path, keywords, description, and service provider. This is crucial for sharing modules within the community. ```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. } } ``` -------------------------------- ### Vue 渲染函数:使用内置组件 (JS - render) Source: https://cn.vuejs.org/guide/extras/render-function.html 在 Vue 渲染函数的 `render` 方法中导入并使用内置组件,如 ``。与 `setup` 方式类似,需要显式导入才能在 `render` 函数中使用这些组件。 ```javascript import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue' export default { render () { return h(Transition, { mode: 'out-in' }, /* ... */) } } ``` -------------------------------- ### Install Tenancy Extension - Shell Source: https://context7_llms Provides the shell commands required to install the multi-tenancy extension for CatchAdmin. This involves using Composer to require the package and then running an artisan command to initialize the tenancy system. ```shell composer require catchadmin/tenancy ``` ```shell php artisan catch:tenant:install ``` -------------------------------- ### Batch Install CatchAdmin Modules Source: https://context7_llms Installs all available CatchAdmin module components in a single command to enhance development efficiency. ```shell php artisan catch:module:install --all ``` -------------------------------- ### Install Vue Project Dependencies Source: https://context7_llms Installs Node.js dependencies for a Vue.js frontend project using Yarn. It also includes configuring the NPM registry to potentially improve download speeds. ```shell cd web # Configure npm registry mirror (for faster downloads, can be skipped if using a proxy) yarn config set registry https://registry.npmmirror.com # Install Vue project npm dependencies yarn install ``` -------------------------------- ### Install JWT Authentication Package (Shell) Source: https://context7_llms This command installs the 'tymon/jwt-auth' package using Composer, which is required for JWT authentication in CatchAdmin versions prior to 3.2.0. After installation, you need to publish the configuration and generate a JWT secret key. ```shell composer require "tymon/jwt-auth" php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret ``` -------------------------------- ### PHP: Configure Redis Connection Source: https://context7_llms Example configuration for connecting to a Redis instance within a PHP environment, likely for a Laravel application. It specifies the client, host, password, and port for the Redis connection. Ensure the PHP Redis extension is installed. ```php #php redis 扩展 REDIS_CLIENT= REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 ``` -------------------------------- ### Python OpenAPI Client for API Requests Source: https://context7_llms This Python code defines an OpenAPI client for making authenticated API requests. It includes methods for creating signatures, building request headers, and sending POST requests. It requires the 'requests' library and assumes the existence of a base URL, app key, and app secret for authentication. The example demonstrates GET and POST request usage and error handling. ```python import requests import time class OpenAPIClient: def __init__(self, app_key, app_secret, base_url): self.app_key = app_key self.app_secret = app_secret self.base_url = base_url def _create_signature(self, data): # This is a placeholder for the actual signature creation logic. # In a real scenario, this would involve sorting parameters, # concatenating them with the app_secret, and hashing. params_string = "&".join([f"{k}={v}" for k, v in sorted(data.items())]) signature = hashlib.sha256(f"{params_string}{self.app_secret}".encode()).hexdigest() return signature def post(self, url, data=None): if data is None: data = {} # Add timestamp data['timestamp'] = int(time.time()) # Generate signature signature = self._create_signature(data) # Build request headers headers = { 'app-key': self.app_key, 'signature': signature, 'Content-Type': 'application/x-www-form-urlencoded' } # Send request full_url = f"{self.base_url}{url}" response = requests.post(full_url, data=data, headers=headers, timeout=30) response.raise_for_status() # Raise an exception for bad status codes return response.json() # Usage Example if __name__ == "__main__": import hashlib # Ensure hashlib is imported for the _create_signature method client = OpenAPIClient( app_key='your_app_key', app_secret='your_app_secret', base_url='https://your-domain.com/api' ) try: # GET request example (assuming a get method exists or is implemented) # result = client.get('/v1/user', {'page': 1, 'limit': 10}) # print(f"GET Result: {result}") # POST request example result = client.post('/v1/user', {'name': 'John', 'email': 'john@example.com'}) print(f"POST Result: {result}") except requests.exceptions.RequestException as e: print(f"Request Error: {e}") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Start Vue Development Server Source: https://context7_llms Starts the Vite development server for the Vue.js frontend project. This command is used to run the frontend in development mode. ```shell yarn dev ``` -------------------------------- ### Vue Router App Component Example Source: https://router.vuejs.org/zh/guide Example of the root `App.vue` component demonstrating the usage of Vue Router's `RouterLink` and `RouterView` components for navigation and rendering route components. It also shows how to access the current route's full path using `$route.fullPath`. ```vue ``` -------------------------------- ### Start Development Server for Uniapp Source: https://context7_llms Starts the development server for the Uniapp project in watch mode. This command allows for live reloading and real-time updates during development. After running, access the compiled output in `dist/dev/mp-weixin`. ```shell pnpm dev:mp ``` -------------------------------- ### Uni-App Page Configuration in pages.json Source: https://context7_llms Example configuration for uni-app pages within the `pages.json` file. It shows how to mark specific pages as requiring login using the `needLogin: true` property. ```json { "pages": [ { "path": "pages/index/index", "type": "home", "style": { "navigationStyle": "custom", "navigationBarTitleText": "首页" } }, { "path": "pages/login/index", "type": "page", "layout": "default" }, { "path": "pages/user/index", "type": "page", "needLogin": true, // 添加需要登录的标记即可 "style": { "navigationStyle": "custom", "navigationBarTitleText": "我的" } } ] } ``` -------------------------------- ### Frontend HTTP Request Methods (Axios Wrapper) Source: https://context7_llms TypeScript examples demonstrating how to use the Http object, a wrapper around axios, for making various types of HTTP requests (GET, POST, PUT, DELETE) in a Vue 3 + TypeScript frontend. ```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) ``` -------------------------------- ### Vue.js: Component Using useFetch Composition Function Source: https://cn.vuejs.org/guide/reusability/composables.html An example of a Vue component script setup that uses the `useFetch` composition function to retrieve data from a specified URL. It imports `useFetch` and then calls it with the URL, destructuring the returned `data` and `error` refs. This demonstrates how to integrate the `useFetch` function into a component's logic for displaying fetched information or error messages. ```vue ``` -------------------------------- ### Install Permissions Module in Laravel Source: https://context7_llms This command installs the permissions module for CatchAdmin, which is necessary for enabling the RBAC (Role-Based Access Control) permission system and dynamic menu features. After installation, refreshing the page may be required to see the new menu items. ```bash php artisan catch:module:install permissions ``` -------------------------------- ### Add Composer Package Dependencies in Installer Source: https://context7_llms Specifies how to automatically install required Composer packages for a CatchAdmin module. This method is called within the module's installer to manage external dependencies. ```php protected function requirePackages(): void { // TODO: Implement requirePackages() method. $this->composer()->require('package/name') } ``` -------------------------------- ### CatchAdmin Module Service Provider Example Source: https://context7_llms A basic example of a module's Service Provider in CatchAdmin. This class is essential for registering module-specific features like routes, events, and middleware. ```php namespace Modules\Test\Providers; use Catch\CatchAdmin; use Catch\Providers\CatchModuleServiceProvider; class TestServiceProvider extends CatchModuleServiceProvider { public function moduleName(): string|array { return 'common'; } } ``` -------------------------------- ### OpenAPI 客户端调用示例 (PHP) Source: https://context7_llms 使用 PHP 实现 OpenAPI 客户端,支持 GET 和 POST 请求。该客户端包含参数扁平化、关联数组判断、签名生成(使用 hash_hmac SHA256)和时间戳添加等功能。输入为 API 的 appKey, appSecret, baseURL,以及请求的 URL 和参数。输出为 API 的响应数据。 ```php appKey = $appKey; $this->appSecret = $appSecret; $this->baseURL = rtrim($baseURL, '/'); } /** * 扁平化数组(与服务端逻辑保持一致) */ private function flattenArray($array, $prefix = '') { $result = []; foreach ($array as $key => $value) { $newKey = $prefix ? $prefix . '.' . $key : $key; if (is_array($value)) { if ($this->isAssociativeArray($value)) { // 关联数组 $result = array_merge($result, $this->flattenArray($value, $newKey)); } else { // 索引数组 foreach ($value as $index => $item) { if (is_array($item)) { $result = array_merge($result, $this->flattenArray($item, $newKey . '[' . $index . ']')); } else { $result[$newKey . '[' . $index . ']'] = $item; } } } } else { $result[$newKey] = $value; } } return $result; } /** * 判断是否为关联数组 */ private function isAssociativeArray($array) { if (empty($array)) { return false; } return array_keys($array) !== range(0, count($array) - 1); } /** * 创建签名(与服务端逻辑完全一致) */ private function createSignature($params) { // 扁平化参数 $flattenedParams = $this->flattenArray($params); // 按键名排序 ksort($flattenedParams); // 构建签名字符串 $signStr = ''; foreach ($flattenedParams as $key => $value) { $signStr .= $key . '=' . $value . '&'; } // 去除末尾的 & 符号 $signStr = rtrim($signStr, '&'); return hash_hmac('sha256', $signStr, $this->appSecret); } /** * GET 请求 */ public function get($url, $params = []) { $params['timestamp'] = time(); $signature = $this->createSignature($params); $query = http_build_query($params); $fullURL = $this->baseURL . $url . '?' . $query; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $fullURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'app-key: ' . $this->appKey, 'signature: ' . $signature ]); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true); } /** * POST 请求 */ public function post($url, $data = []) { $data['timestamp'] = time(); $signature = $this->createSignature($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->baseURL . $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'app-key: ' . $this->appKey, 'signature: ' . $signature, 'Content-Type: application/x-www-form-urlencoded' ]); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true); } } // 使用示例 $client = new OpenAPIClient('your_app_key', 'your_app_secret', 'https://your-domain.com/api'); // GET 请求示例 $result = $client->get('/v1/user', ['page' => 1, 'limit' => 10]); print_r($result); // POST 请求示例 $result = $client->post('/v1/user', ['name' => 'John', 'email' => 'john@example.com']); print_r($result); // 复杂参数示例 $result = $client->post('/v1/user', [ 'user' => ['name' => '张三', 'age' => 25], 'items' => [ ['id' => 1, 'name' => '商品A'], ['id' => 2, 'name' => '商品B'] ] ]); print_r($result); ?> ``` -------------------------------- ### OpenAPI 客户端调用示例 (JavaScript/Node.js) Source: https://context7_llms 使用 JavaScript (Node.js) 实现 OpenAPI 客户端,支持 GET 和 POST 请求。该客户端会自动处理参数扁平化、签名生成和时间戳添加。需要 'crypto' 和 'axios' 库。输入为 API 的 appKey, appSecret, baseURL,以及请求的 URL 和参数。输出为 API 的响应数据。 ```javascript const crypto = require('crypto') const axios = require('axios') class OpenAPIClient { constructor(appKey, appSecret, baseURL) { this.appKey = appKey this.appSecret = appSecret this.baseURL = baseURL } // 扁平化数组 flattenArray(obj, prefix = '') { let result = {} for (let key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key] const newKey = prefix ? `${prefix}.${key}` : key if (Array.isArray(value)) { // 处理数组 value.forEach((item, index) => { if (typeof item === 'object' && item !== null) { Object.assign(result, this.flattenArray(item, `${newKey}[${index}]`)) } else { result[`${newKey}[${index}]`] = item } }) } else if (typeof value === 'object' && value !== null) { // 处理对象 Object.assign(result, this.flattenArray(value, newKey)) } else { result[newKey] = value } } } return result } // 创建签名 createSignature(params) { // 扁平化参数 const flattenedParams = this.flattenArray(params) // 按键名排序 const keys = Object.keys(flattenedParams).sort() // 构建签名字符串 const signStr = keys.map((key) => `${key}=${flattenedParams[key]}`).join('&') return crypto.createHmac('sha256', this.appSecret).update(signStr).digest('hex') } // GET 请求 async get(url, params = {}) { params.timestamp = Math.floor(Date.now() / 1000) const signature = this.createSignature(params) const response = await axios.get(`${this.baseURL}${url}`, { params, headers: { 'app-key': this.appKey, signature: signature } }) return response.data } // POST 请求 async post(url, data = {}) { data.timestamp = Math.floor(Date.now() / 1000) const signature = this.createSignature(data) const response = await axios.post(`${this.baseURL}${url}`, data, { headers: { 'app-key': this.appKey, signature: signature, 'Content-Type': 'application/x-www-form-urlencoded' } }) return response.data } } // 使用示例 const client = new OpenAPIClient('your_app_key', 'your_app_secret', 'https://your-domain.com/api') // GET 请求示例 client .get('/v1/user', { page: 1, limit: 10 }) .then((result) => console.log(result)) .catch((error) => console.error(error)) // POST 请求示例 client .post('/v1/user', { name: 'John', email: 'john@example.com' }) .then((result) => console.log(result)) .catch((error) => console.error(error)) // 复杂参数示例 client .post('/v1/user', { user: { name: '张三', age: 25 }, items: [ { id: 1, name: '商品A' }, { id: 2, name: '商品B' } ] }) .then((result) => console.log(result)) .catch((error) => console.error(error)) ``` -------------------------------- ### Interact with Redis using Laravel Facade (SET and LRANGE commands) Source: https://laravel-docs.catchadmin.com/docs/12/database/redis Examples of using the Redis facade to execute SET and LRANGE commands. The facade supports dynamic method calls that correspond to Redis commands, allowing for direct interaction with the Redis server. ```php use Illuminate\Support\Facades\Redis; Redis::set('name', 'Taylor'); $values = Redis::lrange('names', 5, 10); ``` -------------------------------- ### GET /api/{url} Source: https://context7_llms Performs a GET request to the specified URL with query parameters and authentication headers. ```APIDOC ## GET /api/{url} ### Description Sends a GET request to the API. It automatically adds a timestamp and generates a signature for authentication. The response is returned as a JSON object. ### Method GET ### Endpoint `{baseURL}/{url}` ### Parameters #### Query Parameters - **url** (string) - Required - The specific API endpoint path. - **params** (object) - Optional - A key-value object containing query parameters for the request. This will include 'timestamp' and other user-defined parameters. ### Request Example ```json { "params": { "page": 1, "limit": 10 } } ``` ### Response #### Success Response (200) - **response** (object) - The JSON response from the API. #### Response Example ```json { "data": [ "item1", "item2" ], "meta": { "total": 100, "page": 1, "limit": 10 } } ``` ``` -------------------------------- ### PHP Authentication Exception Example Source: https://context7_llms An example of a concrete exception class inheriting from `ApiAppException`. This specific exception handles authentication failures and maps to the `AUTH_EXCEPTION` code. ```php use App\Enums\Code; class AuthenticationException extends ApiAppException { protected $code = Code::AUTH_EXCEPTION; } ``` -------------------------------- ### Start CatchAdmin Development Environment Source: https://context7_llms A convenience command for CatchAdmin 4.0.0+ to start both the backend PHP development server and the frontend Vue development server concurrently. Use this only if you are not using an existing integrated environment or web server. ```shell composer run dev ``` -------------------------------- ### React Icon Usage Source: https://heroicons.com/ Demonstrates how to import and use Heroicons within a React application. Assumes the heroicons React library is installed. ```jsx import { AcademicCapIcon } from '@heroicons/react/24/solid' function MyComponent() { return (
) } ``` -------------------------------- ### Dynamic Image Response with WEBP format in PHP Source: https://context7_llms Provides an example of how to dynamically respond with an image using the `Image::of()` method. It allows setting dimensions (width and height) and quality, and specifies the output format as WEBP. ```php use Catch\Support\Image\Image; Route::get('image', function () { // 图片的相对地址,默认使用 uploads 磁盘 $path = 'avatars/example.jpg'; return Image::of($path) ->response() // 调用响应 ->width(200) // 设置宽度 ->height(150) // 设置高度(可选) ->quality(80) // 设置质量 ->webp(); // 输出为WEBP格式 }); ``` -------------------------------- ### Interact with Redis using Laravel Facade (GET command) Source: https://laravel-docs.catchadmin.com/docs/12/database/redis This PHP code snippet shows how to retrieve a value from Redis using the Redis facade's 'get' method, which directly maps to the Redis GET command. It's part of a controller that fetches user profile data. ```php Redis::get('user:profile:'.$id) ]); } } ``` -------------------------------- ### CatchAdmin Module Dependency Declaration Source: https://context7_llms Example of declaring module dependencies within the Installer class for a CatchAdmin module. This ensures dependent modules are installed or available. ```php namespace Modules\Shop; use Catch\Support\Module\Installer as ModuleInstaller; use Modules\Shop\Providers\ShopServiceProvider; class Installer extends ModuleInstaller { // Add module dependencies protected function dependencies(): array { return ['member']; } } ``` -------------------------------- ### SmsCode Usage Example Source: https://context7_llms Demonstrates how to use the SmsCode class to send login verification codes. ```APIDOC ## Usage Example: Sending Login SMS Code ### Description This example shows how to instantiate and use the `SmsCode` class to send a login verification code to a specified mobile number. ### Method N/A (Code snippet example) ### Endpoint N/A ### Parameters - **mobile** (string) - Required - The mobile number to send the SMS code to. ### Request Example ```php use App\Http\Controllers\Controller; // Assuming this is within a controller use Illuminate\Http\Request; use Modules\System\Support\Sms\SmsCode; // ... inside a controller method public function sendLoginSms(Request $request) { $smsCode = new SmsCode(); try { $smsCode->login($request->get('mobile')); return response()->json(['message' => 'SMS code sent successfully.']); } catch(\Exception $e) { return response()->json(['error' => $e->getMessage()], 400); } } ``` ### Response #### Success Response - **message** (string) - Indicates the SMS code was sent successfully. #### Response Example ```json { "message": "SMS code sent successfully." } ``` #### Error Response - **error** (string) - Describes the error that occurred during SMS sending. #### Response Example ```json { "error": "Verification code not used or not expired" } ``` ``` -------------------------------- ### CatchTable Object Deep Level Get (JavaScript) Source: https://context7_llms Example demonstrating how to access nested properties within the CatchTable component using dot notation for deep-level property retrieval. This allows for flexible data display from complex objects. ```javascript { prop: 'roles[0].id' } ``` -------------------------------- ### TypeScript: Define and Use Login API Function Source: https://context7_llms Provides an example of defining a reusable `login` API function in TypeScript for a uni-app project. This function encapsulates the POST request logic to the `/login` endpoint, accepting account and password. The example also shows how to import and use this function in a page component. ```typescript export const login = (account: string, password: string) => { return http({ url: `/login`, method: 'POST', data: { account, password, type: 'password' } }) } // 在页面引入 // 首先引入 login 方法 import { login } from '@/api/login' login('account', 'password').then((r) => { // 处理返回的响应 }) ``` -------------------------------- ### GET /v1/user Source: https://context7_llms Fetches user data with optional pagination parameters. ```APIDOC ## GET /v1/user ### Description Fetches user data with optional pagination parameters. ### Method GET ### Endpoint /v1/user ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of items per page. ### Request Example ```json { "page": 1, "limit": 10 } ``` ### Response #### Success Response (200) - **data** (object) - The response payload containing user information. #### Response Example ```json { "status": "success", "data": [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ], "pagination": { "current_page": 1, "total_pages": 5, "total_items": 50 } } ``` ``` -------------------------------- ### cURL for API Requests with Authentication Source: https://context7_llms This bash script demonstrates how to make GET and POST requests to an API using cURL, including signature generation for authentication. It configures API credentials, defines a signature creation function, and constructs requests with appropriate headers and data payloads. The script also shows how to format JSON responses using 'jq'. ```bash #!/bin/bash # Configuration parameters APP_KEY="your_app_key" APP_SECRET="your_app_secret" BASE_URL="https://your-domain.com/api" # Create signature function (consistent with server-side logic) create_signature() { local params="$1" # Note: Parameters in cURL scripts need manual flattening and sorting. # For complex parameters, consider using clients in other languages. echo -n "$params" | openssl dgst -sha256 -hmac "$APP_SECRET" -hex | sed 's/^.* //' } # GET request example echo "=== GET Request Example ===" TIMESTAMP=$(date +%s) PARAMS="page=1&limit=10×tamp=$TIMESTAMP" SIGNATURE=$(create_signature "$PARAMS") curl -X GET \ "$BASE_URL/v1/user?$PARAMS" \ -H "app-key: $APP_KEY" \ -H "signature: $SIGNATURE" \ -H "Content-Type: application/json" echo -e "\n" # POST request example echo "=== POST Request Example ===" TIMESTAMP=$(date +%s) POST_DATA="name=John&email=john@example.com×tamp=$TIMESTAMP" SIGNATURE=$(create_signature "$POST_DATA") curl -X POST \ "$BASE_URL/v1/user" \ -H "app-key: $APP_KEY" \ -H "signature: $SIGNATURE" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "$POST_DATA" echo -e "\n" # Format JSON response using jq (requires jq to be installed) echo "=== Request with Formatted Output ===" TIMESTAMP=$(date +%s) PARAMS="timestamp=$TIMESTAMP" SIGNATURE=$(create_signature "$PARAMS") curl -s -X GET \ "$BASE_URL/v1/user?$PARAMS" \ -H "app-key: $APP_KEY" \ -H "signature: $SIGNATURE" \ | jq '.' ``` -------------------------------- ### PHP: 多租户文件系统配置 Source: https://context7_llms 该 PHP 配置块用于配置多租户文件系统。它定义了将在租户隔离时使用的磁盘后缀基础,以及需要进行租户隔离的磁盘列表(如 uploads, static, certs)。还包括用于本地磁盘的根目录覆盖设置以及是否后缀化 `storage_path()`。 ```php 'filesystem' => [ /** * 在 'disks' 数组中列出的每个磁盘将以 suffix_base 作为后缀,后跟租户 ID。 */ 'suffix_base' => 'tenant-', 'disks' => [ 'uploads', // 上传磁盘 'static', // 静态文件存储磁盘 'certs', // 证书磁盘 ], /** * 对于本地磁盘使用此设置。 * * 请参见 https://tenancyforlaravel.com/docs/v3/tenancy-bootstrappers/#filesystem-tenancy-boostrapper */ 'root_override' => [ // 根目录在 storage_path() 后面加上后缀的磁盘。 'uploads' => '%storage_path%', 'static' => '%storage_path%', 'certs' => '%storage_path%', ], /** * storage_path() 是否应被后缀化。 * * 注意:禁用此设置可能会破坏本地磁盘租户功能。只有在您使用外部文件存储服务(如 S3)时才禁用此设置。 * * 对于绝大多数应用程序,此功能应启用。但在某些边缘情况下,它可能会导致问题(例如在 Vapor 中使用 Passport - 见 #196),因此 * 如果您遇到这些边缘情况问题,您可能希望禁用此功能。 */ 'suffix_storage_path' => true, /** * 默认情况下,asset() 调用也会进行多租户处理。您可以使用 global_asset() 和 mix() * 来获取全局的、非租户特定的资产。然而,当您在租户应用程序中使用 * asset() 调用的包时,可能会遇到一些问题。为避免此类问题,您可以 * 禁用 asset() 辅助函数的租户处理,并在您希望使用租户特定资产(产品图像、头像等)的位置 * 明确使用 tenant_asset() 调用。 */ 'asset_helper_tenancy' => true, ], ``` -------------------------------- ### PHP Example: Retrieving User Permissions Source: https://context7_llms Shows how to retrieve all permissions associated with a user. This is achieved by accessing the `permissions` property of a user object after loading the permissions relationship using `withPermissions()`. This is useful for displaying user roles and capabilities. ```php // 获取用户的所有权限列表 /*@var Model\Roles $user*/ $user->withPermissions()->permissions; ``` -------------------------------- ### PHP OpenAPI Client: GET and POST Requests Source: https://context7_llms This PHP code defines an OpenAPIClient class for interacting with an API. It includes methods for making GET and POST requests, automatically generating signatures, and handling HTTP requests using cURL. The client requires an app key, app secret, and base URL during initialization. ```PHP appKey = $appKey; $this->appSecret = $appSecret; $this->baseURL = rtrim($baseURL, '/') . '/'; } private function createSignature($params) { // In a real scenario, this would involve sorting params and HMAC-SHA256 // For simplicity, a placeholder is used here. return hash_hmac('sha256', http_build_query($params), $this->appSecret); } public function get($url, $params = []) { $params['timestamp'] = time(); $signature = $this->createSignature($params); $queryString = http_build_query($params); $fullUrl = $this->baseURL . $url . '?' . $queryString; $headers = [ 'app-key: ' . $this->appKey, 'signature: ' . $signature ]; return $this->makeRequest($fullUrl, 'GET', $headers); } /** * POST 请求 */ public function post($url, $data = []) { $data['timestamp'] = time(); $signature = $this->createSignature($data); $headers = [ 'app-key: ' . $this->appKey, 'signature: ' . $signature, 'Content-Type: application/x-www-form-urlencoded' ]; $fullUrl = $this->baseURL . $url; return $this->makeRequest($fullUrl, 'POST', $headers, http_build_query($data)); } /** * 执行 HTTP 请求 */ private function makeRequest($url, $method, $headers, $data = null) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_TIMEOUT => 30, ]); if ($data && $method === 'POST') { curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode !== 200) { throw new Exception("HTTP Error: " . $httpCode); } return json_decode($response, true); } } // 使用示例 $client = new OpenAPIClient('your_app_key', 'your_app_secret', 'https://your-domain.com/api'); try { // GET 请求示例 $result = $client->get('/v1/user', ['page' => 1, 'limit' => 10]); echo "GET Result: " . json_encode($result) . "\n"; // POST 请求示例 $result = $client->post('/v1/user', ['name' => 'John', 'email' => 'john@example.com']); echo "POST Result: " . json_encode($result) . "\n"; // 复杂参数示例 $complexParams = [ 'user' => [ 'name' => '张三', 'age' => 25 ], 'items' => [ ['id' => 1, 'name' => '商品A'], ['id' => 2, 'name' => '商品B'] ] ]; $result = $client->post('/v1/user', $complexParams); echo "Complex Result: " . json_encode($result) . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ```