### Complete Resource Controller Example Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/crud/resources.md This example demonstrates a full Resource Controller for managing products. It includes validation rules, data transformation, query filtering, and a custom batch action for updating product status. ```php use Core\Resources\Attribute\Resource; use Core\Resources\Attribute\Action; #[Resource( app: 'admin', route: '/admin/products', name: 'products' )] class ProductController extends Resources { protected string $model = Product::class; /** * 验证规则 */ public function validator(array $data, ServerRequestInterface $request, array $args): array { return [ 'name' => [ ['required', '产品名称不能为空'], ['lengthMin', 2, '产品名称至少2个字符'] ], 'price' => [ ['required', '价格不能为空'], ['numeric', '价格必须是数字'], ['min', 0.01, '价格不能小于0.01'] ], 'category_id' => [ ['required', '分类不能为空'], ['integer', '分类ID必须是整数'] ] ]; } /** * 数据转换 */ public function transform(object $item): array { return [ 'id' => $item->id, 'name' => $item->name, 'price' => $item->price, 'price_formatted' => '¥' . number_format($item->price, 2), 'stock' => $item->stock, 'status' => $item->status, 'status_text' => $item->status ? '上架' : '下架', 'category' => [ 'id' => $item->category->id, 'name' => $item->category->name ], 'created_at' => $item->created_at->format('Y-m-d H:i:s') ]; } /** * 列表查询 */ public function queryMany(Builder $query, ServerRequestInterface $request, array $args): void { $params = \Core\Utils\RequestParam::query($request); // 分类筛选 if (!empty($params['category_id'])) { $query->where('category_id', $params['category_id']); } // 状态筛选 if (isset($params['status']) && $params['status'] !== '') { $query->where('status', $params['status']); } // 预加载分类 $query->with('category'); } /** * 创建后处理 */ public function createAfter(Data $data, mixed $model): void { // 清除分类缓存 \Core\App::cache()->delete("category_{$model->category_id}_products"); } /** * 批量上架 */ #[Action(methods: 'POST', route: '/batch-publish', name: 'batchPublish')] public function batchPublish( ServerRequestInterface $request, ResponseInterface $response, array $args ): ResponseInterface { $data = \Core\Utils\RequestParam::body($request); $ids = $data['ids'] ?? []; if (empty($ids)) { throw new \Core\Handlers\ExceptionBusiness('请选择要上架的产品'); } $count = Product::whereIn('id', $ids)->update(['status' => 1]); return send($response, '批量上架成功', [ 'updated_count' => $count ]); } } ``` -------------------------------- ### Storage Class Usage Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/storage.md Demonstrates how to create a Storage instance and get the storage driver interface. ```APIDOC ## Storage Class ### Description Provides a unified interface for file storage operations. ### Usage ```php use Core\Storage\Storage; // Create a storage instance (e.g., 'local' driver) $storage = new Storage('local', $config); // Get the storage driver interface $driver = $storage->getInstance(); ``` ``` -------------------------------- ### Start Development Server Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md Use PHP's built-in web server to run your application during development. This command starts the server on `localhost:8000`, serving files from the `public` directory. ```bash # 使用 PHP 内置服务器 php -S localhost:8000 -t public ``` -------------------------------- ### Install DuxLite Starter Project Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md Use Composer to create a new project from the DuxLite starter template. This is the recommended way to begin. ```bash # 创建新项目 composer create-project duxweb/dux-lite-starter my-app cd my-app # 设置权限 chmod -R 755 data/ chmod +x dux # 创建开发配置 cp config/use.toml config/use.dev.toml cp config/database.toml config/database.dev.toml ``` -------------------------------- ### Install AMQP Messenger Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/queues.md Install the AMQP Messenger component using Composer for AMQP (RabbitMQ) backend support. ```bash composer require symfony/amqp-messenger ``` -------------------------------- ### Traditional Integration Mode - Page Example Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/template/frontend.md An example of a user list page (`user/list.latte`) using the base template in the traditional integration mode, demonstrating how to loop through users and display data. ```APIDOC ## Traditional Integration Mode - Page Example ```html {layout 'layouts/base.latte'} {block content}

用户管理

{foreach $users as $user} {/foreach}
姓名 邮箱 状态 操作
{$user->name} {$user->email} {$user->status ? '正常' : '禁用'} 编辑 删除
{/block} ``` ``` -------------------------------- ### Resource Middleware Configuration Example (Member) Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/crud/resource-routes.md Configures resource routes for the member system, setting up authentication and permission middleware for members. ```php // 会员系统配置 \Core\App::resource()->set( "member", (new Resource('member', '/member'))->addAuthMiddleware( new AuthMiddleware("member"), // 会员认证 new PermissionMiddleware("member", \App\Models\Member::class) // 会员权限 ) ); ``` -------------------------------- ### Frontend-Backend Separation Mode - API Controller Example Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/template/frontend.md Example of an API controller (`ApiUserController`) for managing users in the frontend-backend separation mode, demonstrating the use of DuxLite's resource controller for automatic RESTful API generation. ```APIDOC ## Frontend-Backend Separation Mode - API Controller Example ```php #[Resource( app: 'api', route: '/api/users', name: 'users' )] class ApiUserController extends Resources { protected string $model = User::class; // 自动生成RESTful API: // GET /api/users -> 用户列表 // POST /api/users -> 创建用户 // PUT /api/users/{id} -> 更新用户 // DELETE /api/users/{id} -> 删除用户 } ``` ``` -------------------------------- ### Install Redis Messenger Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/queues.md Install the Redis Messenger component using Composer for Redis backend support. ```bash composer require symfony/redis-messenger ``` -------------------------------- ### Resource Middleware Configuration Example (API) Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/crud/resource-routes.md Configures resource routes for the API, integrating authentication and permission middleware for general users. ```php // API接口配置 \Core\App::resource()->set( "api", (new Resource('api', '/api'))->addAuthMiddleware( new AuthMiddleware("api"), // API认证 new PermissionMiddleware("api", \App\Models\User::class) // 用户权限 ) ); ``` -------------------------------- ### Cache Configuration Example Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/data/cache.md Configure the cache type, prefix, and default lifetime in config/use.toml. Redis requires additional database configuration. ```toml [cache] type = "file" prefix = "cache_" defaultLifetime = 3600 ``` -------------------------------- ### Resource Middleware Configuration Example (Admin) Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/crud/resource-routes.md Configures resource routes for the admin application, including authentication and permission middleware for administrators. ```php // 管理后台配置 \Core\App::resource()->set( "admin", (new Resource('admin', '/admin'))->addAuthMiddleware( new AuthMiddleware("admin"), // 管理员认证 new PermissionMiddleware("admin", \App\Models\Admin::class) // 管理员权限 ) ); ``` -------------------------------- ### Production Environment Application Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/environment.md Example TOML configuration for the application and cache settings in a production environment. ```toml [app] name = "我的应用" debug = false secret = "production-secret-key-32-chars" timezone = "Asia/Shanghai" lang = "zh-CN" domain = "https://myapp.com" [cache] type = "redis" prefix = "prod_cache_" defaultLifetime = 7200 ``` -------------------------------- ### Start Worker Mode Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/performance.md Start the application in Worker mode to improve performance by keeping the application resident in memory. This can provide a 3-10x performance boost. ```bash # 启动 Worker 提升性能 ./dux worker:start --port=8080 --workers=4 ``` -------------------------------- ### Production Environment Database and Redis Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/environment.md Example TOML configuration for database and Redis connections in a production environment. ```toml [db.drivers.default] driver = "mysql" host = "db.example.com" port = 3306 database = "myapp_prod" username = "app_user" password = "secure-password-here" charset = "utf8mb4" [redis.drivers.default] host = "redis.example.com" port = 6379 password = "redis-password" database = 0 ``` -------------------------------- ### Development Environment Application Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/environment.md Example TOML configuration for the application and cache settings in a development environment. ```toml [app] name = "我的应用-开发版" debug = true secret = "dev-secret-key-32-characters" timezone = "Asia/Shanghai" lang = "zh-CN" domain = "http://localhost:8000" [cache] type = "file" prefix = "dev_cache_" defaultLifetime = 3600 ``` -------------------------------- ### Run Web Application Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/lifecycle.md Executes the web application by loading modules, routes, booting plugins, and starting the web server. This is used for HTTP requests. ```php public static function runWeb() { self::$bootstrap->loadApp(); // 加载应用模块 self::$bootstrap->loadRoute(); // 加载路由配置 Plugin::boot(self::$bootstrap); // 插件启动 self::$bootstrap->runWeb(); // 启动 Web 服务 } ``` -------------------------------- ### Development Environment Database and Redis Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/environment.md Example TOML configuration for database and Redis connections in a development environment. ```toml [db.drivers.default] driver = "mysql" host = "localhost" port = 3306 database = "myapp_dev" username = "root" password = "" charset = "utf8mb4" [redis.drivers.default] host = "localhost" port = 6379 password = "" database = 1 ``` -------------------------------- ### Create Basic Authentication Middleware Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/middleware.md A simplified example of an authentication middleware that checks for a valid token before proceeding with the request handling. ```php class AuthMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $token = $this->extractToken($request); if (!$token || !$this->validateToken($token)) { throw new \Core\Handlers\ExceptionBusiness('Unauthorized', 401); } return $handler->handle($request); } } ``` -------------------------------- ### Create New DuxLite Application Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/overview.md Use Composer to create a new DuxLite project from the starter template. Navigate into the project directory and start the development server. ```bash composer create-project duxweb/dux-lite-starter my-app cd my-app && php -S localhost:8000 -t public curl http://localhost:8000/hello ``` -------------------------------- ### Environment Requirements Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md Ensure you have the necessary PHP version and Composer installed. Also, verify that the required PHP extensions (PDO and zlib) are enabled. ```bash # 必需环境 PHP >= 8.4 Composer >= 2.0 # 必需扩展 ext-pdo, ext-zlib ``` -------------------------------- ### Run Command-Line Application Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/lifecycle.md Executes the command-line application by loading modules, routes, commands, booting plugins, and starting the command execution. This is used for CLI operations. ```php public static function run() { self::$bootstrap->loadApp(); // 加载应用模块 self::$bootstrap->loadRoute(); // 加载路由配置 self::$bootstrap->loadCommand(); // 加载命令行 Plugin::boot(self::$bootstrap); // 插件启动 self::$bootstrap->run(); // 运行命令行 } ``` -------------------------------- ### Start Queue Management Process Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/queues.md Initiate the queue management process to monitor and manage workers. This command reads configurations from config/queue.toml. ```bash # 启动队列管理进程(读取 config/queue.toml 的 workers.*,并周期显示队列状态) php dux queue:start # 只启动指定 work php dux queue:start queueA queueB # 禁用状态输出 php dux queue:start --no-status ``` -------------------------------- ### Alibaba Cloud OSS Storage Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/storage.md Example configuration for Alibaba Cloud OSS, demonstrating S3 compatibility. Requires bucket, domain, endpoint, and credentials. ```toml # 阿里云 OSS 配置示例 [drivers.oss] type = "s3" bucket = "my-oss-bucket" domain = "https://my-oss-bucket.oss-cn-hangzhou.aliyuncs.com" endpoint = "oss-cn-hangzhou.aliyuncs.com" region = "oss-cn-hangzhou" ssl = true version = "latest" access_key = "your-access-key-id" secret_key = "your-access-key-secret" ``` -------------------------------- ### Basic Linux/macOS Permissions Setup Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/directory-structure.md These commands set basic permissions for the `data/` directory and the `dux` executable on Linux/macOS. Ensure the web server has appropriate read/write access. ```bash # 基本权限设置 chmod -R 755 data/ chmod +x dux ``` -------------------------------- ### Manually Install DuxLite Core Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md If you prefer to set up the project structure manually, use Composer to require the DuxLite core package and create the basic directory structure. ```bash # 安装核心包 composer require duxweb/dux-lite # 创建基本结构 mkdir -p {config,data,public} ``` -------------------------------- ### Create First Controller Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md Define a controller class, such as `HelloController`, and use the `#[Route]` attribute to map HTTP methods and routes to controller actions. This example includes routes for '/hello' and '/hello/{name}'. ```php getBody()->write('Hello, DuxLite!'); return $response; } #[Route(methods: 'GET', route: '/hello/{name}')] public function greet(ServerRequestInterface $request, ResponseInterface $response, string $name): ResponseInterface { $response->getBody()->write("Hello, {$name}!"); return $response; } } ``` -------------------------------- ### Create Basic Auth Middleware Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/middleware.md Example of creating a custom middleware for authentication. It checks for an Authorization header, validates the token, and adds user information to the request. ```php getHeaderLine('Authorization'); if (empty($token)) { throw new \Core\Handlers\ExceptionBusiness('Token required', 401); } // 验证 Token 并添加用户信息 $user = $this->validateToken($token); $request = $request->withAttribute('user', $user); // 继续处理请求 $response = $handler->handle($request); // 响应后处理 return $response->withHeader('X-Auth-User', $user->name); } private function validateToken(string $token): object { // Token 验证逻辑 return (object)['id' => 1, 'name' => 'User']; } } ``` -------------------------------- ### Register Application Modules Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md Specify the modules to be registered by listing their fully qualified class names in `config/app.toml`. This example registers the `App\Web\App` module. ```toml registers = ["App\\Web\\App"] ``` -------------------------------- ### Looping Constructs in Latte Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/template/views.md Demonstrates how to iterate over arrays or collections using 'foreach'. Includes examples with indices, the '$iterator' variable for first/last/counter/count, and handling empty lists. ```html
    {foreach $posts as $index => $post}
  1. {$post->title}
  2. {/foreach}
{foreach $posts as $post}

{$post->title}

{$post->excerpt}

第 {$iterator->counter} / {$iterator->count} 篇 {$post->created_at|date:'Y-m-d'}
{else}

暂无文章

{/foreach}
{foreach $categories as $category}

{$category->name}

{foreach $category->posts as $post}

{$post->title}

{$post->excerpt}

{else}

该分类下暂无文章

{/foreach}
{/foreach} ``` -------------------------------- ### Organizing App Code by Functionality Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/directory-structure.md Example of organizing the `app/` directory by feature or functionality. Each feature (e.g., User, Product, Order) has its own subdirectory with an `App.php` class and controllers. ```directory app/ ├── User/ # 用户管理 │ ├── App.php │ └── Controllers/ ├── Product/ # 产品管理 │ ├── App.php │ └── Controllers/ └── Order/ # 订单处理 ├── App.php └── Controllers/ ``` -------------------------------- ### Nginx Server Configuration for Performance Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/performance.md Example Nginx configuration to enhance performance by enabling Gzip compression and setting long-term caching for static assets. ```nginx # Nginx 配置示例 server { # 启用 Gzip gzip on; gzip_types text/plain application/json application/javascript text/css; # 静态文件缓存 location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; add_header Cache-Control "public, immutable"; } } ``` -------------------------------- ### Designing for Testability with Mocks Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/dependency-injection.md Design your application for testability by allowing dependencies to be easily replaced with mock objects during testing. This example shows how to conditionally register a mock repository. ```php // Production environment registration public function register(Bootstrap $bootstrap): void { if (!App::di()->has('userRepository')) { App::di()->set('userRepository', function() { return new DatabaseUserRepository(App::db()); }); } } // Inject Mock during testing App::di()->set('userRepository', new MockUserRepository()); ``` -------------------------------- ### Environment Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/performance.md Manage application settings based on the environment using separate configuration files. This example shows production and development configurations for debug mode and secret keys. ```toml # config/use.toml - 生产环境 [app] debug = false secret = "%env(APP_SECRET)%" # config/use.dev.toml - 开发环境 [app] debug = true secret = "dev-secret-key" ``` -------------------------------- ### Getting the DI Container Instance Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/dependency-injection.md Obtain the DI container instance using the App::di() static method. This is the entry point for managing services. ```php use Core\App; // 获取容器实例 $container = App::di(); ``` -------------------------------- ### Basic Cache Operations Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/data/cache.md Demonstrates setting, getting, checking, deleting, and clearing cache entries. Use a TTL for specific expiry times or omit for permanent caching. ```php $cache = App::cache(); // 设置缓存 $cache->set('user.123', $userData, 3600); // 缓存1小时 $cache->set('config.app', $appConfig); // 永久缓存 // 获取缓存 $userData = $cache->get('user.123'); $appConfig = $cache->get('config.app', []); // 带默认值 // 检查和删除 if ($cache->has('user.123')) { $cache->delete('user.123'); } // 清空所有缓存 $cache->clear(); ``` -------------------------------- ### Test Database and Redis Connection (PHP) Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/configuration.md Test your database and Redis connections using the provided PHP snippets. These examples help diagnose service connection failures by attempting to establish and verify connections. ```php // 测试数据库连接 try { $db = App::db(); echo "数据库连接成功\n"; } catch (Exception $e) { echo "数据库连接失败: " . $e->getMessage() . "\n"; } // 测试 Redis 连接 try { $redis = App::redis(); $redis->ping(); echo "Redis 连接成功\n"; } catch (Exception $e) { echo "Redis 连接失败: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Organizing App Code by Business Domain Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/directory-structure.md Example of organizing the `app/` directory by business domain. This structure groups related functionalities under broader categories like Frontend, Backend, or Integration. ```directory app/ ├── Frontend/ # 前台业务 │ ├── App.php │ └── Controllers/ ├── Backend/ # 后台管理 │ ├── App.php │ └── Controllers/ └── Integration/ # 第三方集成 ├── App.php └── Controllers/ ``` -------------------------------- ### Instantiate Storage Manager Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/storage.md How to create an instance of the Storage manager with a specific driver and configuration. ```php use Core\Storage\Storage; // 创建存储实例 $storage = new Storage('local', $config); // 获取存储驱动接口 $driver = $storage->getInstance(); ``` -------------------------------- ### Application Initialization Logic Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/lifecycle.md Handles loading environment variables, initializing the dependency injection container, registering core services, and setting up global functions and configurations. ```php public static function init() { // 1. 加载环境变量(可选) $dotenv = Dotenv::createImmutable(self::$basePath); $dotenv->safeLoad(); // 安全加载,不会覆盖现有变量 // 2. 初始化依赖注入容器 self::$di = new Container(); // 3. 创建 Bootstrap 实例 self::$bootstrap = new \Core\Bootstrap(); // 4. 注册基础服务 self::$bootstrap->registerFunc(); // 注册公共函数 self::$bootstrap->registerConfig(); // 注册公共配置 self::$bootstrap->registerWeb(); // 注册 Web 服务 self::$bootstrap->registerPlugin(); // 注册插件 Plugin::register(self::$bootstrap); // 插件初始化 } ``` -------------------------------- ### Initialize Application with Basic Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/lifecycle.md Sets up fundamental application parameters like language, timezone, and debug mode, and defines critical paths. This is the entry point for DuxLite applications. ```php App::create( basePath: dirname(__DIR__), lang: 'zh-CN', timezone: 'Asia/Shanghai', host: "0.0.0.0", debug: true, logo: '' ); ``` -------------------------------- ### User Profile Endpoint Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/template/routing.md Handles GET and POST requests for the user profile. It allows fetching query parameters, POST data, headers, server information, and cookies. For POST requests, it processes form submissions and updates the profile; for GET requests, it displays the profile form. ```APIDOC ## GET /profile ### Description Retrieves the user profile form. Allows fetching query parameters like 'tab' to display specific sections of the profile. ### Method GET ### Endpoint /profile ### Parameters #### Query Parameters - **tab** (string) - Optional - Specifies which tab of the profile to display (e.g., 'basic'). ### Response #### Success Response (200) Returns a rendered HTML template for the user profile. #### Response Example (HTML content for the profile page) ## POST /profile ### Description Processes the submission of the user profile form. Updates the user's information based on the provided POST data and redirects back to the profile page. ### Method POST ### Endpoint /profile ### Parameters #### Request Body - **field1** (type) - Required/Optional - Description (Details of fields depend on the form submission, e.g., 'tab', 'username', 'email'). ### Request Example ```json { "tab": "basic", "username": "new_username", "email": "new_email@example.com" } ``` ### Response #### Success Response (302) Redirects the user to the profile page, typically with a status code of 302. #### Response Example (HTTP 302 Redirect to /profile?tab=basic) ``` -------------------------------- ### Web Application Entry Point Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md Create the `public/index.php` file to handle web requests. It includes the autoloader, creates the application instance, and runs it. ```php size(string $path): int ``` -------------------------------- ### Retrieving Service Configurations Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/configuration.md Demonstrates how to obtain configuration instances for various services like cache, database, Redis, and queue using their respective App facade methods. ```php // 缓存服务配置 $cache = App::cache(); // 使用默认配置 $cache = App::cache('redis'); // 指定类型 // 数据库服务配置 $db = App::db(); // 使用默认连接 // Redis 服务配置 $redis = App::redis(); // 默认连接 $redis = App::redis('cache'); // 指定连接名 // 队列服务配置 $queue = App::queue(); // 使用默认配置 ``` -------------------------------- ### StorageInterface: Get Public URL Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/storage.md Generates a publicly accessible URL for a file. ```php // 获取公共访问URL // $path: 文件路径,返回可直接访问的URL $storage->publicUrl(string $path): string ``` -------------------------------- ### Web Application Entry Point Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/directory-structure.md The `index.php` file in the `public/` directory serves as the web application's entry point. It bootstraps the DuxLite application. ```php // public/index.php - Web 应用入口 privateUrl(string $path, int $expires = 3600): string ``` -------------------------------- ### Reading Application and Database Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/configuration.md Demonstrates how to read application and database configurations using the App::config() method. Supports reading nested configurations and providing default values. ```php // 读取应用配置 $config = App::config('use'); $appName = $config->get('app.name'); $debug = $config->get('app.debug', false); // 带默认值 // 读取数据库配置 $dbConfig = App::config('database'); $host = $dbConfig->get('db.drivers.default.host'); // 读取嵌套配置 $cacheConfig = App::config('use')->get('cache', []); $cacheType = $cacheConfig['type'] ?? 'file'; ``` -------------------------------- ### Get Request Headers Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/api/controllers.md Illustrates how to access various request headers like User-Agent, Authorization, Content-Type, and Accept-Language. ```APIDOC ## GET /request-info ### Description Retrieves information about the incoming request, including headers. ### Method GET ### Endpoint /request-info ### Response #### Success Response (200) - **user_agent** (string) - The User-Agent header value. - **content_type** (string) - The Content-Type header value. - **accept_language** (string) - The Accept-Language header value. #### Response Example { "example": "{\"user_agent\": \"PostmanRuntime/7.28.0\", \"content_type\": \"application/json\", \"accept_language\": \"en-US,en;q=0.9\"}" } ``` -------------------------------- ### Get Request Headers Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/api/controllers.md Extracts specific headers from the incoming HTTP request, such as User-Agent, Authorization, Content-Type, and Accept-Language. ```php public function handleRequest( ServerRequestInterface $request, ResponseInterface $response, array $args ): ResponseInterface { // 获取请求头 $userAgent = $request->getHeaderLine('User-Agent'); $authorization = $request->getHeaderLine('Authorization'); $contentType = $request->getHeaderLine('Content-Type'); $acceptLanguage = $request->getHeaderLine('Accept-Language'); return send($response, '请求头获取成功', [ 'user_agent' => $userAgent, 'content_type' => $contentType, 'accept_language' => $acceptLanguage ]); } ``` -------------------------------- ### Configuration File Structure Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/environment.md Illustrates the directory structure for DuxLite configuration files, including environment-specific files. ```bash config/ ├── use.toml # 生产环境应用配置 ├── use.dev.toml # 开发环境应用配置 ├── database.toml # 生产环境数据库配置 ├── database.dev.toml # 开发环境数据库配置 ├── queue.toml # 队列配置(可选) └── server.toml # 服务器配置 ``` -------------------------------- ### Get Cache Instance Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/data/cache.md Obtain the default cache driver or a specific driver like 'redis' using App::cache(). ```php use Core\App; // 获取默认缓存驱动 $cache = App::cache(); // 获取指定缓存驱动(目前内置支持 file/redis) $redisCache = App::cache('redis'); ``` -------------------------------- ### Log Application Boot Information Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/lifecycle.md Logs information about the application boot process, including memory usage and the number of modules loaded. Use this to monitor application startup. ```php public function boot(Bootstrap $bootstrap): void { App::log()->info('Application boot completed', [ 'memory_usage' => memory_get_usage(true), 'modules_loaded' => count(App::$registerApp) ]); } ``` -------------------------------- ### Application Configuration (Development) Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/quick-start.md Configure your application settings, including name, debug mode, secret key, and domain, in the `config/use.dev.toml` file. Also, set up cache type and prefix. ```toml [app] name = "我的应用" debug = true secret = "your-32-char-secret-key-here" domain = "http://localhost:8000" [cache] type = "file" prefix = "myapp_" ``` -------------------------------- ### Database and Redis Configuration Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/configuration.md Set up database connections and Redis instances. Supports environment variable injection for sensitive details like host, port, username, and password. Multiple Redis instances can be configured for different purposes like default, cache, and queue. ```toml # 数据库连接配置 [db.drivers.default] driver = "mysql" host = "%env(DB_HOST)%" port = "%env(DB_PORT)%" database = "%env(DB_DATABASE)%" username = "%env(DB_USERNAME)%" password = "%env(DB_PASSWORD)%" charset = "utf8mb4" collation = "utf8mb4_unicode_ci" prefix = "" ``` ```toml # Redis 配置(支持多个连接) [redis.drivers.default] host = "localhost" port = 6379 password = "" database = 0 timeout = 2.5 # optPrefix 是可选的键前缀 optPrefix = "" ``` ```toml [redis.drivers.cache] host = "localhost" port = 6379 password = "" database = 1 timeout = 2.5 optPrefix = "cache_" ``` ```toml # 队列专用 Redis(队列配置实际上使用 database.toml 中的 Redis 配置) [redis.drivers.queue] host = "localhost" port = 6379 password = "" database = 2 timeout = 2.5 optPrefix = "queue_" ``` ```toml # AMQP 配置(RabbitMQ) [amqp.drivers.default] host = "localhost" port = 5672 vhost = "/" username = "guest" password = "guest" persisted = false prefix = "" ``` -------------------------------- ### Export User Data Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/crud/resources.md Exports user data to a CSV file. This action is accessible via a GET request to the /export route. ```APIDOC ## GET /export ### Description Exports user data to a CSV file. ### Method GET ### Endpoint /export ### Response #### Success Response (200) - **download_url** (string) - URL to download the generated CSV file. ``` -------------------------------- ### Batch Cache Operations Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/data/cache.md Perform multiple cache set, get, or delete operations efficiently using setMultiple, getMultiple, and deleteMultiple. ```php // 批量设置 $values = [ 'user.1' => $user1Data, 'user.2' => $user2Data, ]; $cache->setMultiple($values, 3600); // 批量获取和删除 $results = $cache->getMultiple(['user.1', 'user.2'], []); $cache->deleteMultiple(['user.1', 'user.2']); ``` -------------------------------- ### Start Single Worker Consumer Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/system/queues.md Run a single worker to consume tasks from a specific queue and priority. This is suitable for use with process managers. ```bash # 单 worker 模式(只消费一个队列,适合自行用守护进程拉起多份) php dux queue:consume queueA high ``` -------------------------------- ### Get Status (skip auth and permission check) Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/crud/resources.md Retrieves the service status. This action is completely public and does not require authentication or permission checks. ```APIDOC ## GET /status ### Description Retrieves the service status. This action is completely public and does not require authentication or permission checks. ### Method GET ### Endpoint /status ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the service is operational. ``` -------------------------------- ### Get Query Parameters Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/api/controllers.md Retrieves and processes query parameters from the incoming request, including pagination and search criteria, to build a database query. ```php public function getUsers( ServerRequestInterface $request, ResponseInterface $response, array $args ): ResponseInterface { // 获取查询参数 $params = \Core\Utils\RequestParam::query($request); $page = (int) ($params['page'] ?? 1); $limit = (int) ($params['limit'] ?? 20); $search = $params['search'] ?? ''; // 构建查询 $query = User::query(); if ($search) { $query->where('name', 'like', "%{$search}%"); } // 使用框架的分页方法 + 统一格式化 $users = $query->paginate($limit); ["data" => $data, "meta" => $meta] = format_data($users, function ($item) { return $item->transform(); }); return send($response, '获取成功', $data, $meta); } ``` -------------------------------- ### Recommended Service Naming Conventions Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/dependency-injection.md Follow recommended naming conventions for services in the dependency injection container. Use dot notation for hierarchical names and avoid overly short or capitalized names. ```php // ✅ Recommended naming App::di()->set('user.service', $userService); App::di()->set('payment.gateway.stripe', $stripeGateway); App::di()->set('cache.redis', $redisCache); // ❌ Avoided naming App::di()->set('UserService', $userService); // Starts with uppercase App::di()->set('user_service', $userService); // Underscore separator App::di()->set('us', $userService); // Too short ``` -------------------------------- ### Retrieving Services from the DI Container Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/dependency-injection.md Fetch registered services using the get() method. Use has() to check for existence before retrieval to avoid errors. ```php // 获取服务 $userService = App::di()->get('userService'); // 检查服务是否存在 if (App::di()->has('userService')) { $userService = App::di()->get('userService'); } ``` -------------------------------- ### TOML Placeholders for Environment Variables and PHP Functions Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/configuration.md Demonstrates how to use placeholders in TOML files to dynamically inject environment variables and call PHP functions for configuration values. ```toml [app] # 环境变量占位符 secret = "%env(APP_SECRET)%" name = "%env(APP_NAME)%" [database.drivers.default] # 环境变量配置 host = "%env(DB_HOST)%" username = "%env(DB_USERNAME)%" password = "%env(DB_PASSWORD)%" database = "%env(DB_DATABASE)%" [storage.drivers.local] # 函数调用占位符(支持 base_path/app_path/data_path/public_path/config_path 等) root = "%public_path(uploads)%" # 混合文本和占位符 log_file = "logs/app_%date(Y-m-d)%.log" [cache] # 时间戳占位符 prefix = "cache_%time()%_" ``` -------------------------------- ### Batch Processing with Chunking Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/performance.md Process large datasets in chunks to prevent memory exhaustion. The example demonstrates exporting users by processing them in batches of 1000. ```php // 批量处理避免内存溢出 class DataExportService { public function exportUsers(): void { User::chunk(1000, function ($users) { foreach ($users as $user) { $this->processUser($user); } }); } } ``` -------------------------------- ### Get Public Info (skip permission check, requires auth) Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/crud/resources.md Retrieves public information. This action requires authentication but skips permission checks. ```APIDOC ## GET /public-info ### Description Retrieves public information. Requires authentication but skips permission checks. ### Method GET ### Endpoint /public-info ### Response #### Success Response (200) - **info** (object) - The public information. ``` -------------------------------- ### Get Request Body Data and Validate Source: https://github.com/duxweb/dux-lite/blob/v2/docs/reference/api/controllers.md Retrieves and validates data from the request body using a defined schema before creating a new user record. ```php public function createUser( ServerRequestInterface $request, ResponseInterface $response, array $args ): ResponseInterface { // 获取请求体数据 $data = \Core\Utils\RequestParam::body($request); // 数据验证 $validated = \Core\Validator\Validator::parser($data, [ 'name' => [ ['required', '姓名不能为空'], ['lengthMin', 2, '姓名至少需要2个字符'] ], 'email' => [ ['required', '邮箱不能为空'], ['email', '邮箱格式不正确'] ], 'status' => [ ['optional', '状态值可选'], ['integer', '状态值必须是整数'] ] ]); // 创建用户(使用验证后的数据) $user = User::create([ 'name' => $validated->name, 'email' => $validated->email, 'status' => (int) ($validated->status ?? 1) ]); return send($response, '创建成功', $user->transform(), [], 201); } ``` -------------------------------- ### External Dependencies: Databases, Caching, and Queues Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/environment.md Outlines the external dependencies for databases, caching, and queues, including version recommendations. ```bash # 数据库(选择之一) MySQL >= 8.0 PostgreSQL >= 13 SQLite >= 3.35 # 缓存(可选) Redis >= 6.0 # 队列(可选) RabbitMQ >= 3.8 ``` -------------------------------- ### Minimum and Recommended System Requirements Source: https://github.com/duxweb/dux-lite/blob/v2/docs/guide/environment.md Specifies the minimum and recommended system requirements for PHP, memory, and disk space. ```bash # 最低要求 PHP >= 8.4 Memory >= 128M Disk >= 1GB # 推荐配置 PHP >= 8.4 Memory >= 512M Disk >= 10GB ```