### Create CGI Controller with Routing (PHP) Source: https://context7.com/iamfat/gini/llms.txt Extend \Gini\Controller\CGI to create web page controllers. This class supports middleware (e.g., 'auth', 'csrf') and pre-action hooks for tasks like authentication. It defines routes for different actions (e.g., __index for GET /article, actionView for GET /article/view/{id}, actionCreate for POST /article/create) and uses Gini's view rendering and response mechanisms. ```php redirect('login'); return false; } } // GET /article public function __index() { $articles = those('article') ->orderBy('created_at', 'desc') ->limit(10); return new \Gini\CGI\Response\HTML(V('article/list', [ 'articles' => $articles ])); } // GET /article/view/{id} public function actionView($id) { $article = a('article', $id); if (!$article->id) { throw new \Gini\CGI\Response\NotFoundException(); } return new \Gini\CGI\Response\HTML(V('article/view', [ 'article' => $article ])); } // POST /article/create public function actionCreate() { $form = $this->form('post'); $article = a('article'); $article->title = $form['title']; $article->content = $form['content']; $article->author = a('user', $_SESSION['user_id']); $article->save(); $this->redirect('article/view/' . $article->id); } } ``` -------------------------------- ### Gini REST: RESTful API Client and Server Implementation (PHP) Source: https://github.com/iamfat/gini/blob/master/README.md Provides examples of setting up RESTful API communication using the Gini framework. It covers the client code for sending HTTP requests and the server code for defining and responding to RESTful endpoints. ```php // Client $rest = new \Gini\REST('http://localhost/rest'); $sum = $rest->post('add', ['a'=>1, 'b'=>2]); // Server class Hello extends \Gini\Controller\REST { public function postAdd($a, $b) { return $a + $b; } } ``` -------------------------------- ### JSON-RPC Service Controller Source: https://context7.com/iamfat/gini/llms.txt Implement JSON-RPC APIs by extending `\Gini\Controller\API`. Methods starting with `action` are exposed as RPC endpoints. ```APIDOC ## JSON-RPC Service Controller Inherit from `\Gini\Controller\API` to create JSON-RPC API controllers. ### Methods Methods starting with `action` are exposed as RPC endpoints. #### `actionGetInfo($userId)` **Description:** Retrieves user information by user ID. **Parameters:** - **userId** (int) - The ID of the user to retrieve. **Response (Success):** - **id** (int) - The user's ID. - **name** (string) - The user's name. - **email** (string) - The user's email. **Response (Error):** - Throws `\Gini\API\Exception` with status 404 if the user is not found. #### `actionCreate($name, $email)` **Description:** Creates a new user. **Parameters:** - **name** (string) - The name of the new user. - **email** (string) - The email of the new user. **Response (Success):** - **id** (int) - The ID of the newly created user. - **success** (boolean) - Indicates if the creation was successful. **Response (Error):** - Throws `\Gini\API\Exception` with status 500 if creation fails. #### `actionList($page = 1, $limit = 20)` **Description:** Retrieves a list of users with pagination. **Parameters:** - **page** (int) - The page number for pagination (default: 1). - **limit** (int) - The number of users per page (default: 20). **Response (Success):** - An array of user objects, each containing: - **id** (int) - The user's ID. - **name** (string) - The user's name. ``` -------------------------------- ### Use REST Client for API Calls (PHP) Source: https://context7.com/iamfat/gini/llms.txt The \Gini\REST class facilitates making HTTP requests (GET, POST, PUT, DELETE, PATCH) to RESTful APIs. It supports query parameters, JSON and form data payloads, custom headers, and cookie persistence. The client is initialized with the base URL of the API. ```php get('users/123'); echo $user['name']; // 带查询参数的 GET $users = $rest->get('users', ['page' => 1, 'limit' => 10]); // POST 请求 (默认 JSON 格式) $newUser = $rest->post('users', [ 'name' => '张三', 'email' => 'zhangsan@example.com' ]); echo $newUser['id']; // 表单格式 POST $result = $rest->form()->post('login', [ 'username' => 'admin', 'password' => 'secret' ]); // PUT 更新 $rest->put('users/123', ['name' => '李四']); // DELETE 删除 $rest->delete('users/123'); // PATCH 部分更新 $rest->patch('users/123', ['status' => 'inactive']); // 自定义请求头 $rest->header('Authorization', 'Bearer token123'); $protectedData = $rest->get('protected/resource'); // 启用 Cookie 支持 $rest->enableCookie(); ``` -------------------------------- ### Utilize Gini CLI Tools Source: https://context7.com/iamfat/gini/llms.txt Covers common CLI commands for application management and demonstrates how to create custom CLI controllers for automated tasks. ```bash gini app create myapp gini composer install gini cache gini web start gini myapp do-something gini ci phpunit test gini orm sync gini app info ``` ```php namespace Gini\Controller\CLI; class Task extends \Gini\Controller\CLI { public function actionProcess($type = 'default') { echo "处理任务类型: $type\n"; $tasks = those('task') ->whose('type')->is($type) ->andWhose('status')->is('pending'); foreach ($tasks as $task) { $task->status = 'completed'; $task->save(); echo "完成任务: {$task->id}\n"; } } } ``` -------------------------------- ### CGI Controller and Routing Source: https://context7.com/iamfat/gini/llms.txt Create web page controllers by extending `\Gini\Controller\CGI`. Supports middleware and view rendering. ```APIDOC ## CGI Controller and Routing Inherit from `\Gini\Controller\CGI` to create web page controllers, supporting middleware and view rendering. ### Controller Configuration #### `middlewares` Define an array of middleware names to be applied to controller actions. ```php public $middlewares = ['auth', 'csrf']; ``` #### `__preAction($action, &$params)` **Description:** A pre-action hook that runs before any action is executed. Useful for authentication and authorization. **Parameters:** - **action** (string) - The name of the action being called. - **params** (array) - The parameters passed to the action. **Return Value:** - `false` to prevent the action from executing. ### Actions #### `__index()` **Description:** Handles the default index action (e.g., `GET /article`). Renders a list of articles. **Response:** - Returns a `\Gini\CGI\Response\HTML` object rendering the 'article/list' view. #### `actionView($id)` **Description:** Handles viewing a specific article (e.g., `GET /article/view/{id}`). **Parameters:** - **id** (int) - The ID of the article to view. **Response:** - Returns a `\Gini\CGI\Response\HTML` object rendering the 'article/view' view. **Response (Error):** - Throws `\Gini\CGI\Response\NotFoundException` if the article is not found. #### `actionCreate()` **Description:** Handles creating a new article (e.g., `POST /article/create`). **Request Body:** - **title** (string) - The title of the article. - **content** (string) - The content of the article. **Action:** - Saves the new article and redirects to the article's view page. ``` -------------------------------- ### Create JSON-RPC Server Controller (PHP) Source: https://context7.com/iamfat/gini/llms.txt Extend \Gini\Controller\API to create JSON-RPC API controllers. Methods intended for RPC calls must be prefixed with 'action'. Handles user data retrieval, creation, and listing with error handling for non-existent users and creation failures. ```php id) { throw new \Gini\API\Exception('用户不存在', 404); } return [ 'id' => $user->id, 'name' => $user->name, 'email' => $user->email ]; } public function actionCreate($name, $email) { $user = a('user'); $user->name = $name; $user->email = $email; if ($user->save()) { return ['id' => $user->id, 'success' => true]; } throw new \Gini\API\Exception('创建失败', 500); } public function actionList($page = 1, $limit = 20) { $offset = ($page - 1) * $limit; $users = those('user') ->orderBy('id', 'desc') ->limit($offset, $limit); $result = []; foreach ($users as $user) { $result[] = ['id' => $user->id, 'name' => $user->name]; } return $result; } } ``` -------------------------------- ### ORM Object Management with a() Source: https://context7.com/iamfat/gini/llms.txt The a() function is the primary entry point for instantiating, retrieving, updating, and deleting database records in Gini. ```php name; // 输出: 张三 echo $user->email; // 输出: zhangsan@example.com // 创建新用户对象 $newUser = a('user'); $newUser->name = '李四'; $newUser->email = 'lisi@example.com'; $newUser->save(); // 保存到数据库 echo $newUser->id; // 输出: 自动生成的ID // 通过条件数组获取对象 $admin = a('user', ['role' => 'admin', 'status' => 'active']); echo $admin->name; // 删除对象 $user = a('user', 123); $user->delete(); ``` -------------------------------- ### REST Service Controller Source: https://context7.com/iamfat/gini/llms.txt Implement RESTful APIs by extending `\Gini\Controller\REST`. Methods like `getDefault`, `postDefault`, `putDefault`, `deleteDefault` handle corresponding HTTP methods. ```APIDOC ## REST Service Controller Inherit from `\Gini\Controller\REST` to create RESTful API controllers. ### Endpoints and Methods #### `getDefault($id = null)` **Description:** Handles GET requests. - If `$id` is provided, retrieves a specific resource (e.g., `GET /users/{id}`). - If `$id` is null, retrieves a list of resources (e.g., `GET /users`). **Response (Success): - For single resource: Object with user details (`id`, `name`). - For list: Array of user objects (`id`, `name`). **Response (Error):** - Throws `\Gini\CGI\Response\Exception` with status 404 if the user is not found. #### `postDefault()` **Description:** Handles POST requests to create a new resource (e.g., `POST /users`). **Request Body:** - **name** (string) - The name of the user. - **email** (string) - The email of the user. **Response (Success):** - **id** (int) - The ID of the newly created user. - **created** (boolean) - Indicates if the creation was successful. #### `putDefault($id)` **Description:** Handles PUT requests to update an existing resource (e.g., `PUT /users/{id}`). **Parameters:** - **id** (int) - The ID of the user to update. **Request Body:** - **name** (string) - The new name for the user (optional). **Response (Success):** - **updated** (boolean) - Indicates if the update was successful. #### `deleteDefault($id)` **Description:** Handles DELETE requests to remove a resource (e.g., `DELETE /users/{id}`). **Parameters:** - **id** (int) - The ID of the user to delete. **Response (Success):** - **deleted** (boolean) - Indicates if the deletion was successful. ``` -------------------------------- ### Gini RPC: JSON-RPC Client and Server Implementation (PHP) Source: https://github.com/iamfat/gini/blob/master/README.md Illustrates how to implement JSON-RPC communication within the Gini framework. It shows both the client-side code for making remote procedure calls and the server-side code for defining and handling these calls. ```php // Client $rpc = new \Gini\RPC('http://gini/api'); $sum = $rpc->hello->add(1, 2); //Server class Hello extends \Gini\Controller\API { public function actionAdd($a, $b) { return $a + $b; } } ``` -------------------------------- ### Configuration Management with Gini Source: https://context7.com/iamfat/gini/llms.txt The \Gini\Config class handles reading and managing configuration files, supporting YAML and PHP formats. It allows retrieval of configuration values, setting runtime configurations, and appending values to existing configurations. It also supports environment variable substitution. ```php ``` -------------------------------- ### Implement PSR-3 Logging in Gini Source: https://context7.com/iamfat/gini/llms.txt Demonstrates how to use the Gini Logger class to record various log levels and configure log handlers via YAML files. It supports multiple outputs like SysLog and File logging. ```php $logger = \Gini\Logger::of('app'); $logger->debug('调试信息: {data}', ['data' => $debugData]); $logger->info('用户 {user} 登录成功', ['user' => $username]); $logger->notice('配置已更新'); $logger->warning('磁盘空间不足: {free}MB', ['free' => $freeSpace]); $logger->error('数据库连接失败: {error}', ['error' => $exception->getMessage()]); $logger->critical('支付服务不可用'); $logger->alert('系统负载过高'); $logger->emergency('系统崩溃'); ``` -------------------------------- ### Manage Sessions in Gini Source: https://context7.com/iamfat/gini/llms.txt Provides methods for session lifecycle management, including opening, setting data, generating secure tokens, and configuring storage backends like Redis. ```php \Gini\Session::open(); $_SESSION['user_id'] = 123; $token = \Gini\Session::tempToken('csrf_', 30); \Gini\Session::makeTimeout('temp_data', 300); \Gini\Session::regenerateId(); \Gini\Session::cleanup(); \Gini\Session::close(); ``` -------------------------------- ### REST Client Usage Source: https://context7.com/iamfat/gini/llms.txt Use the `\Gini\REST` class to make HTTP requests to RESTful APIs. ```APIDOC ## REST Client Usage Use the `\Gini\REST` class to make HTTP requests to RESTful APIs. ### Initialization ```php $rest = new \Gini\REST('http://api.example.com/v1'); ``` ### HTTP Methods #### GET ```php // Get a specific resource $user = $rest->get('users/123'); // Get a list of resources with query parameters $users = $rest->get('users', ['page' => 1, 'limit' => 10]); ``` #### POST ```php // Send JSON data (default) $newUser = $rest->post('users', [ 'name' => '张三', 'email' => 'zhangsan@example.com' ]); // Send form data $result = $rest->form()->post('login', [ 'username' => 'admin', 'password' => 'secret' ]); ``` #### PUT ```php // Update a resource $rest->put('users/123', ['name' => '李四']); ``` #### DELETE ```php // Delete a resource $rest->delete('users/123'); ``` #### PATCH ```php // Partially update a resource $rest->patch('users/123', ['status' => 'inactive']); ``` ### Advanced Usage #### Custom Headers ```php $rest->header('Authorization', 'Bearer token123'); $protectedData = $rest->get('protected/resource'); ``` #### Cookie Support ```php $rest->enableCookie(); ``` ``` -------------------------------- ### Create REST Server Controller (PHP) Source: https://context7.com/iamfat/gini/llms.txt Extend \Gini\Controller\REST to build RESTful API controllers. This class maps HTTP methods and URL segments to controller methods like getDefault, postDefault, putDefault, and deleteDefault. It handles retrieving resources by ID, listing resources, creating, updating, and deleting them, with support for form data parsing and response exceptions. ```php id) { throw new \Gini\CGI\Response\Exception('用户不存在', 404); } return ['id' => $user->id, 'name' => $user->name]; } // GET /users - 列表 $users = those('user')->limit(20); $result = []; foreach ($users as $user) { $result[] = ['id' => $user->id, 'name' => $user->name]; } return $result; } // POST /users public function postDefault() { $form = $this->form('post'); $user = a('user'); $user->name = $form['name']; $user->email = $form['email']; $user->save(); return ['id' => $user->id, 'created' => true]; } // PUT /users/{id} public function putDefault($id) { $user = a('user', $id); $form = $this->form('post'); $user->name = $form['name'] ?? $user->name; $user->save(); return ['updated' => true]; } // DELETE /users/{id} public function deleteDefault($id) { $user = a('user', $id); $user->delete(); return ['deleted' => true]; } } ``` -------------------------------- ### JSON-RPC Client Implementation Source: https://context7.com/iamfat/gini/llms.txt The Gini\RPC class allows for seamless JSON-RPC 2.0 communication with remote services using a fluent method-call syntax. ```php user->getInfo(123); echo $result['name']; // 带命名参数调用 $result = $rpc->order->create(['product_id' => 100, 'quantity' => 2]); // 设置连接超时 $rpc->connectTimeout(2000); // 使用配置中的 RPC 服务 $paymentRpc = \Gini\RPC::of('payment'); $result = $paymentRpc->transaction->process(['amount' => 100.00]); // 自定义请求头 $rpc->setHeader(['Authorization' => 'Bearer token123']); $result = $rpc->protected->resource(); ``` -------------------------------- ### Gini ORM: Object-Relational Mapping with Natural Language Syntax (PHP) Source: https://github.com/iamfat/gini/blob/master/README.md Demonstrates the Gini framework's built-in ORM, 'Those ORM', which allows developers to interact with databases using object-oriented principles and a natural language-like query syntax. It abstracts SQL operations into object methods. ```php // 查询所有名字以'J'开头, 爸爸的email中存在genee的用户 $users = those('users') ->whose('name')->beginWith('J') ->andWhose('father')->isIn( those('users')->whose('email')->contains('genee') ); ``` -------------------------------- ### IoC Container with Gini Source: https://context7.com/iamfat/gini/llms.txt The \Gini\IoC class implements a Dependency Injection container, supporting dependency injection and singleton patterns. It allows binding interfaces to implementations, registering singletons, and directly instantiating objects. ```php set('key', 'value'); // Clear binding \Gini\IoC::clear('\App\Services\UserService'); ?> ``` -------------------------------- ### View Rendering with Gini Source: https://context7.com/iamfat/gini/llms.txt The `V()` function is used to create view objects, supporting PHP and Phtml template engines. It allows rendering views with data and returning HTML or JSON responses. Views can also have their variables assigned dynamically. ```php 'Article List', 'articles' => $articles ]); echo $html; // Return HTML response in a controller return new \Gini\CGI\Response\HTML(V('user/profile', [ 'user' => $user, 'orders' => $orders ])); // Return JSON response return new \Gini\CGI\Response\JSON([ 'success' => true, 'data' => $result ]); // Example view template (view/article/list.phtml): // //