### Think-Helper Installation Source: https://doc.thinkphp.cn/v6_1/thinkzhushougongjuku.html Instructions on how to install the think-helper library using Composer. ```APIDOC ## Think-Helper Installation ### Description Install the think-helper library using Composer. ### Method Composer require ### Endpoint N/A ### Request Example ```bash composer require topthink/think-helper ``` ### Response N/A ``` -------------------------------- ### Executing a ThinkPHP Console Command Source: https://doc.thinkphp.cn/v6_1/rukouwenjian.html Example of how to execute a console command using the console entry file. This command checks the installed ThinkPHP version. ```bash php think version ``` -------------------------------- ### Start SocketLog Server Locally Source: https://doc.thinkphp.cn/v6_1/yuanchengtiaoshi.html Install and run the SocketLog server locally using npm. This command starts a WebSocket service on port 1229 for debugging. ```bash npm install -g socketlog-server socketlog-server ``` -------------------------------- ### Install Multi-App Extension Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Install the think-multi-app extension for multi-application mode. ```bash composer require topthink/think-multi-app ``` -------------------------------- ### Install think-helper Source: https://doc.thinkphp.cn/v6_1/thinkzhushougongjuku.html Install the think-helper library using Composer. This provides string and array manipulation utilities. ```bash composer require topthink/think-helper ``` -------------------------------- ### Start HTTP Service with think-swoole Source: https://doc.thinkphp.cn/v6_1/Swoole.html Start the HTTP server directly from the command line. The server defaults to running on 0.0.0.0:80. Configuration can be adjusted in config/swoole.php. ```bash php think swoole ``` -------------------------------- ### Install Trace Extension Source: https://doc.thinkphp.cn/v6_1/yemianTrace.html Install the page Trace extension using Composer. This command excludes development dependencies, preventing the installation of the page Trace extension. ```bash composer install --no-dev ``` -------------------------------- ### Install think-annotation Extension Source: https://doc.thinkphp.cn/v6_1/zhujieyanzheng.html Install the `topthink/think-annotation` extension using Composer to enable annotation-based routing and validation. ```bash composer require topthink/think-annotation ``` -------------------------------- ### Install think-swoole Extension Source: https://doc.thinkphp.cn/v6_1/Swoole.html Install the think-swoole extension using Composer after installing the Swoole extension. Note that Swoole does not support Windows environments. ```bash composer require topthink/think-swoole ``` -------------------------------- ### Install think-socketlog Extension Source: https://doc.thinkphp.cn/v6_1/yuanchengtiaoshi.html Install the SocketLog extension using Composer. This is the first step to enable remote debugging. ```bash composer require topthink/think-socketlog ``` -------------------------------- ### Blog Controller for Resource Routes Source: https://doc.thinkphp.cn/v6_1/ziyuanluyou.html Example controller methods corresponding to the default resource route actions. ```php | get | | | [] | [] | | hello/ | index/hello | get | index/hello | | {"ext":"html"} | [] | | blog | Blog/index | get | Blog/index | | {"complete_match":true} | [] | | blog | Blog/save | post | Blog/save | | {"complete_match":true} | [] | | blog/create | Blog/create | get | Blog/create | | [] | [] | | blog//edit | Blog/edit | get | Blog/edit | | [] | [] | | blog/ | Blog/read | get | Blog/read | | [] | [] | | blog/ | Blog/update | put | Blog/update | | [] | [] | | blog/ | Blog/delete | delete | Blog/delete | | [] | [] | +----------------+-------------+--------+-------------+--------+-------------------------+---------+ ``` -------------------------------- ### URL Access Example (Without Auto Multi-App) Source: https://doc.thinkphp.cn/v6_1/luyou.html Demonstrates the URL format for accessing a route when automatic multi-application mode is disabled. ```text http://serverName/index.php/hello/think ``` -------------------------------- ### Install Composer on Linux/Mac Source: https://doc.thinkphp.cn/v6_1/anzhuangThinkPHP.html Use this command to install Composer globally on Linux and Mac OS X systems. ```bash curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer ``` -------------------------------- ### Example Query Options Structure Source: https://doc.thinkphp.cn/v6_1/huoquchaxuncanshu.html The getOptions() method returns an array representing the query parameters, including conditions, fields, and other settings. ```json { "json": [], "json_assoc": false, "field_type": [], "soft_delete": ["__TABLE__.delete_time", ["=", 0]], "where": { "AND": [ ["sass_uid", "=", "61011ed0c9610"], ["hold_time", ">=", 1630252800, null], ["hold_time", "<=", 1630339199, null], ["custom_status", "=", 0] ] } } ``` -------------------------------- ### Install ThinkPHP 6.0 Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Use Composer to create a new ThinkPHP 6.0 project. ```bash composer create-project topthink/think:6.0.0 tp ``` -------------------------------- ### Load Database Configuration Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Example of loading database configuration parameters into the route configuration using `Db::name()` and `Config::set()`. ```php $config = Db::name('config')->column('value', 'name'); Config::set($config, 'route'); ``` -------------------------------- ### Route Definition Example Source: https://doc.thinkphp.cn/v6_1/luyou.html An example of defining a route in ThinkPHP. This rule maps the URL '/hello/:name' to the 'index/hello' action. ```php Route::rule('hello/:name', 'index/hello'); ``` -------------------------------- ### Correct Access Example Source: https://doc.thinkphp.cn/v6_1/zhujieyanzheng.html Accessing the endpoint with the required 'name' parameter will result in a successful response. ```bash http://127.0.0.1:8000/hello?name=zhans ``` -------------------------------- ### Get GET Parameters using input() Source: https://doc.thinkphp.cn/v6_1/shurubianliang.html Retrieve single GET variables, all GET variables, or GET variables with filtering using the `input()` function. The second argument can specify a default value and a filter function. ```php // 获取单个变量 input('get.id'); ``` ```php // 使用过滤方法获取 默认为空字符串 input('get.name'); ``` ```php // 获取全部变量 input('get.'); ``` -------------------------------- ### Boot Method for Service Initialization Source: https://doc.thinkphp.cn/v6_1/xitongfuwu.html The `boot` method is called after all services are registered. It can be used for startup operations and supports dependency injection. This example registers a route and extends the `Validate` class. ```php get('captcha/[:config]', "\\think\\captcha\\CaptchaController@index"); Validate::maker(function ($validate) { $validate->extend('captcha', function ($value) { return captcha_check($value); }, ':attribute错误!'); }); } } ``` -------------------------------- ### Define and Use Command Options Source: https://doc.thinkphp.cn/v6_1/zidingyiminglingxing.html Example of adding an option to a command and how to call the command with different argument styles. It also shows how to retrieve the option's value within the command logic. ```php ->addOption('adminname', 'p', Option::VALUE_OPTIONAL, '管理员账号') ``` ```bash // 无需任何参数 php think install // 使用全名参数 php think install --adminuser admin // 使用缩写 php think install -u admin ``` ```php $input->getOption('adminname'); ``` -------------------------------- ### Get Configuration Parameter (Old vs New) Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Demonstrates the change in how to retrieve configuration parameters, from `Config::pull()` to `Config::get()`. ```php Config::pull('app'); ``` ```php Config::get('app'); ``` -------------------------------- ### Install ThinkPHP 6.0 Development Version Source: https://doc.thinkphp.cn/v6_1/anzhuangThinkPHP.html Install the latest development version (6.0.x-dev) of ThinkPHP, which is useful for learning and accessing the most recent updates. ```bash composer create-project topthink/think=6.0.x-dev tp ``` -------------------------------- ### URL Access Example (With Auto Multi-App) Source: https://doc.thinkphp.cn/v6_1/luyou.html Shows the URL format for accessing a route when automatic multi-application mode is enabled. Note the inclusion of the application name. ```text http://serverName/index.php/index/hello/think ``` -------------------------------- ### Register Service by Binding Class Source: https://doc.thinkphp.cn/v6_1/xitongfuwu.html Implement the `register` method in a service class to bind a service to the container. This example binds 'file_system' to the `FileSystem` class. ```php app->bind('file_system', FileSystem::class); } } ``` -------------------------------- ### Using Cache Helper Functions Source: https://doc.thinkphp.cn/v6_1/huancun.html Demonstrates basic cache operations using the `cache()` helper function for setting, getting, deleting, and retrieving the cache instance. ```php // Set cache data cache('name', $value, 3600); // Get cache data var_dump(cache('name')); // Delete cache data cache('name', NULL); // Return cache object instance $cache = cache(); ``` -------------------------------- ### Access Localhost with Built-in Server Source: https://doc.thinkphp.cn/v6_1/anzhuangThinkPHP.html After starting the built-in server, access your application via this URL in a web browser. ```bash http://localhost:8000/ ``` -------------------------------- ### Get Nested Configuration Parameter Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Shows how to access nested configuration parameters, which now requires specifying the full path. ```php Config::get('exception_handle'); ``` ```php Config::get('app.exception_handle'); ``` -------------------------------- ### Define GET Route with Cache Source: https://doc.thinkphp.cn/v6_1/qingqiuhuancun.html Set a 3600-second cache for a GET route. Subsequent accesses to the same URL will return cached data with a 304 status code. ```php Route::get('new/:id','News/read')->cache(3600); ``` -------------------------------- ### Define GET Route with Dynamic Cache Identifier Source: https://doc.thinkphp.cn/v6_1/qingqiuhuancun.html Configure a GET route with a 3600-second cache, using dynamic parameters from the request (e.g., ':id', ':page') to create a unique cache identifier. ```php Route::get('new/:id','News/read')->cache([ 'new/:id/:page', 3600 ]); ``` -------------------------------- ### Simplified URL Example after Binding Source: https://doc.thinkphp.cn/v6_1/luyoubangding.html Demonstrates how a URL can be simplified after binding it to a controller or action. The original URL structure is no longer required for access. ```http http://serverName/blog/read/id/5 ``` ```http http://serverName/read/id/5 ``` ```http http://serverName/5 ``` -------------------------------- ### Nested Resource Route URLs Source: https://doc.thinkphp.cn/v6_1/ziyuanluyou.html Examples of URLs for nested resource routes, showing how parent resource IDs are included. ```plaintext http://serverName/blog/128/comment/32 http://serverName/blog/128/comment/32/edit ``` -------------------------------- ### Comment Controller for Nested Resource Source: https://doc.thinkphp.cn/v6_1/ziyuanluyou.html Example controller methods for a nested resource, demonstrating how parent IDs are passed. ```php domain('news'); ``` -------------------------------- ### Run ThinkPHP Built-in Server Source: https://doc.thinkphp.cn/v6_1/anzhuangThinkPHP.html Start the ThinkPHP built-in development server to test your application. This command runs the server on the default port. ```bash php think run ``` -------------------------------- ### Route Definition File Location (Multi-App) Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Specifies the location of route definition files in a multi-application setup. ```php app/index/route/route.php // index应用的路由定义文件 app/index/route/web.php // index应用的第二个路由定义文件 app/admin/route/route.php // admin应用的路由定义文件 ``` -------------------------------- ### Model Query Example Source: https://doc.thinkphp.cn/v6_1/dingyi.html Demonstrates how to perform a query using a model, which is an enhanced version of the database query builder. The result is a model dataset instead of a plain array. ```php User::where('id','>',10)->select(); ``` -------------------------------- ### addOption Method Source: https://doc.thinkphp.cn/v6_1/zidingyiminglingxing.html Details the `addOption` method used for adding options to console commands, including its parameters and usage examples. ```APIDOC ## addOption ``` /** * Add an option * @param string $name Option name * @param string $shortcut Alias * @param int $mode Type * @param string $description Description * @param mixed $default Default value * @return Command */ public function addOption(string $name, string $shortcut = null, int $mode = null, string $description = '', $default = null) ``` ### Example Defined as follows: ``` ->addOption('adminname', 'p', Option::VALUE_OPTIONAL, 'Administrator account') ``` It can be called like this: ``` // No parameters required php think install // Use full name parameter php think install --adminuser admin // Use abbreviation php think install -u admin ``` In the command logic, you can get it like this: ``` $input->getOption('adminname'); ``` ``` -------------------------------- ### Validate Expiration Date Range Source: https://doc.thinkphp.cn/v6_1/neizhiguize.html The 'expire' rule checks if the current operation falls within a specified start and end date. Example: 'expire_time' => 'expire:2016-2-1,2016-10-01'. ```php 'expire_time' => 'expire:2016-2-1,2016-10-01' ``` -------------------------------- ### Define Route with Batch Route Parameters using option() Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Demonstrates setting multiple route parameters ('ext' and 'https') using the 'option' method for cleaner configuration. ```php Route::get('new/:id', 'News/read') ->option([ 'ext' => 'html', 'https' => true ]); ``` -------------------------------- ### Define Route with Closure Matching Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that uses a closure for matching logic. The route will not match if the closure returns false. ```php Route::get('new/:id', 'News/read') ->match(function(Rule $rule,Request $request) { // 如果返回false 则视为不匹配 return false; }); ``` -------------------------------- ### Configure Trace Tabs Source: https://doc.thinkphp.cn/v6_1/yemianTrace.html Customize the Trace tabs by modifying the 'trace.php' configuration file. This example shows how to add a 'user' tab and merge 'error|notice|warning' into a single '错误' tab. ```php return [ 'type' => 'Html', 'tabs' => [ 'base' => '基本', 'file' => '文件', 'info' => '流程', 'error' => '错误', 'sql' => 'SQL', 'debug' => '调试', 'user' => '用户', ], ]; ``` ```php return [ 'type' => 'Html', 'tabs' => [ 'base' => '基本', 'file' => '文件', 'error|notice|warning' => '错误', 'sql' => 'SQL', 'debug|info' => '调试', ], ]; ``` -------------------------------- ### Calling Console Commands in Controllers Source: https://doc.thinkphp.cn/v6_1/zidingyiminglingxing.html This section demonstrates how to invoke console commands directly from controller action methods in ThinkPHP 6.1. It includes an example of calling a 'hello' command and fetching its output. ```APIDOC ## Calling Console Commands in Controllers Supports directly calling commands in controller action methods. For example: ```php fetch(); } } ``` After accessing this operation method, for example: ``` http://serverName/index/hello/name/thinkphp ``` The page will output: ``` Hello thinkphp! ``` ``` -------------------------------- ### Configure Composer with Aliyun Mirror Source: https://doc.thinkphp.cn/v6_1/anzhuangThinkPHP.html Configure Composer to use the Aliyun mirror for faster package downloads. This is recommended due to potential slow speeds from the default Composer repository. ```bash composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ ``` -------------------------------- ### Get Relationship Count with withCount Source: https://doc.thinkphp.cn/v6_1/guanliantongji.html Use `withCount` to get the count of related records. The count is automatically added as a dynamic property named `relation_count`. ```php $list = User::withCount('cards')->select([1,2,3]); foreach($list as $user){ // 获取用户关联的card关联统计 echo $user->cards_count; } ``` -------------------------------- ### Generate Service Class with Command Source: https://doc.thinkphp.cn/v6_1/xitongfuwu.html Use the command line to generate a new system service class. This command creates a basic service file with register and boot methods. ```bash php think make:service FileSystemService ``` -------------------------------- ### Mixed Query Example Source: https://doc.thinkphp.cn/v6_1/gaojichaxun.html Combine various query methods, including closures for nested conditions, to build complex queries. Ensure proper syntax for nested queries. ```PHP Db::table('think_user') ->where('name', 'like', 'thinkphp%') ->where(function ($query) { $query->where('id', '<', 10); }) ->select(); ``` ```SQL SELECT * FROM `think_user` WHERE `name` LIKE 'thinkphp%' AND ( `id` < 10 ) ``` -------------------------------- ### Define GET Route with Cache Tag Source: https://doc.thinkphp.cn/v6_1/qingqiuhuancun.html Set a 3600-second cache for a GET route and assign it a cache tag 'page'. This allows for unified cache clearing based on the tag. ```php Route::get('new/:id','News/read')->cache([ 'new/:id/:page', 3600, 'page' ]); ``` -------------------------------- ### Switching Cache Types with Cache::store() Source: https://doc.thinkphp.cn/v6_1/huancun.html Shows how to dynamically switch between different cache types (e.g., file and Redis) using the `Cache::store()` method. This is useful when you need to use specific cache configurations. ```php // Use file cache Cache::set('name','value',3600); Cache::get('name'); // Use Redis cache Cache::store('redis')->set('name','value',3600); Cache::store('redis')->get('name'); // Switch to file cache Cache::store('default')->set('name','value',3600); Cache::store('default')->get('name'); ``` -------------------------------- ### Get Single User Record by ID Source: https://doc.thinkphp.cn/v6_1/chaxun.html Retrieves a single user record by its primary key. Returns `null` if not found. Use `findOrEmpty` to get an empty model instance instead. ```php // 取出主键为1的数据 $user = User::find(1); echo $user->name; ``` ```php // 使用查询构造器查询满足条件的数据 $user = User::where('name', 'thinkphp')->find(); echo $user->name; ``` ```php $user = User::findOrEmpty(1); ``` ```php $user = User::where('name', 'thinkphp')->findOrEmpty(); if (!$user->isEmpty()) { echo $user->name; } ``` -------------------------------- ### Get Variables from Specific Request Types Source: https://doc.thinkphp.cn/v6_1/shurubianliang.html Specify the request type (e.g., 'get', 'post') as the second argument to `only` to retrieve variables from that specific type. This is equivalent to using `Request::get()` or `Request::post()`. ```php Request::only(['id','name'], 'get'); ``` ```php Request::get(['id', 'name']); ``` ```php Request::only(['id','name'], 'post'); ``` ```php Request::post(['id', 'name']); ``` -------------------------------- ### Global Service Registration in service.php Source: https://doc.thinkphp.cn/v6_1/xitongfuwu.html Register system services globally by defining them in the `service.php` file in your application's global public directory. The system automatically handles registration and booting. ```php return [ '\app\service\ConfigService', '\app\service\CacheService', ]; ``` -------------------------------- ### Resource Route URLs Source: https://doc.thinkphp.cn/v6_1/ziyuanluyou.html Examples of URLs that can be accessed with the basic resource route definition. ```plaintext http://serverName/blog/ http://serverName/blog/128 http://serverName/blog/28/edit ``` -------------------------------- ### Define Route with HTTPS Requirement Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that strictly requires HTTPS access. ```php Route::get('new/:id', 'News/read') ->https(); ``` -------------------------------- ### Route Definition (Method Format - Recommended) Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Demonstrates the recommended method-based approach for defining routes. ```php Route::get('hello/:name', 'index/hello'); ``` -------------------------------- ### Enable Debug Mode via .env File Source: https://doc.thinkphp.cn/v6_1/anzhuangThinkPHP.html To enable debug mode for local development, create a `.env` file in the application's root directory. The `.example.env` file provided after installation can be renamed and modified. ```ini APP_DEBUG=true ``` -------------------------------- ### Get Multiple Relationship Counts Source: https://doc.thinkphp.cn/v6_1/guanliantongji.html You can specify multiple relationships for counting by passing an array to `withCount`. ```php $list = User::withCount(['cards', 'phone'])->select([1,2,3]); foreach($list as $user){ // 获取用户关联关联统计 echo $user->cards_count; echo $user->phone_count; } ``` -------------------------------- ### Define Route with JSON Request Requirement Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that only matches if the request is a JSON request. ```php Route::get('new/:id', 'News/read') ->json(); ``` -------------------------------- ### 对象化调用容器实例 Source: https://doc.thinkphp.cn/v6_1/rongqiheyilaizhuru.html 使用`app()`获取容器对象实例,并可以通过属性访问容器中的对象。也可以注册新的容器对象实例。 ```php $app = app(); // 判断对象实例是否存在 isset($app->cache); // 注册容器对象实例 $app->cache = \think\Cache::class; // 获取容器中的对象实例 $cache = $app->cache; ``` -------------------------------- ### Define Route with Domain Matching Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that is only valid when accessed via the 'news.thinkphp.cn' domain. ```php Route::get('new/:id', 'News/read') ->domain('news.thinkphp.cn'); ``` -------------------------------- ### Dynamic Configuration Setting (Deprecated) Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Illustrates a deprecated method for dynamically setting configuration parameters. ```php Config::set('route.default_return_type', 'json'); ``` -------------------------------- ### Configure SocketLog Driver in log.php Source: https://doc.thinkphp.cn/v6_1/yuanchengtiaoshi.html Configure the 'SocketLog' driver in your log.php configuration file. This sets up the connection to the SocketLog server. ```php return [ 'type' => 'SocketLog', 'host' => 'slog.thinkphp.cn', //日志强制记录到配置的client_id 'force_client_ids' => [], //限制允许读取日志的client_id 'allow_client_ids' => [], ] ``` -------------------------------- ### Define Route with Multiple URL Suffixes Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that accepts either '.shtml' or '.html' suffixes. ```php Route::get('new/:id', 'News/read') ->ext('shtml|html'); ``` -------------------------------- ### 注册全局容器回调 Source: https://doc.thinkphp.cn/v6_1/rongqiheyilaizhuru.html 使用`Container::getInstance()->resolving()`方法注册一个全局回调函数,该函数会在容器实例化任何对象时被调用。 ```php Container::getInstance()->resolving(function($instance,$container) { // ... }); ``` -------------------------------- ### Define Route with URL Suffix and HTTPS Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that requires a '.html' suffix and HTTPS access. ```php Route::get('new/:id', 'News/read') ->ext('html') ->https(); ``` -------------------------------- ### Define Nested Resource Routes Source: https://doc.thinkphp.cn/v6_1/ziyuanluyou.html Register nested resource routes, for example, comments belonging to a blog post. ```php Route::resource('blog', 'Blog'); Route::resource('blog.comment','Comment'); ``` -------------------------------- ### 通过对象化调用访问容器类方法 Source: https://doc.thinkphp.cn/v6_1/rongqiheyilaizhuru.html 可以直接通过`app()->类名`的方式访问容器中的类实例,并调用其方法,例如访问配置类或Session类。 ```php // 调用配置类 app()->config->get('app_name'); // 调用session类 app()->session->get('user_name'); ``` -------------------------------- ### Create Data with Field Whitelist using `create()` Source: https://doc.thinkphp.cn/v6_1/xinzeng.html When using the static `create()` method, you can provide a second argument as an array of allowed fields to control which data is written to the database. ```php // 只允许写入name和email字段的数据 $user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ], ['name', 'email']); echo $user->name; echo $user->email; echo $user->id; // 获取自增ID ``` -------------------------------- ### Create and Write Data using Static `create()` Method Source: https://doc.thinkphp.cn/v6_1/xinzeng.html The static `create()` method instantiates a model, assigns data, and saves it in one step. It returns the model instance and automatically filters non-table fields. ```php $user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); echo $user->name; echo $user->email; echo $user->id; // 获取自增ID ``` -------------------------------- ### Route Options and Patterns (Old vs New) Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html Compares the old method of passing options and patterns as array arguments to `Route::get()` with the new chained method calls. ```php Route::get('hello/:name', 'index/hello', [ 'ext' => 'html'], [ 'name' => '\w+']); ``` ```php Route::get('hello/:name', 'index/hello') ->ext('html') ->pattern([ 'name' => '\w+']); ``` -------------------------------- ### Registering Services in Extension Composer.json Source: https://doc.thinkphp.cn/v6_1/xitongfuwu.html To register system services within an extension, add a `services` entry in the `extra.think` section of the extension's `composer.json` file. After installing the extension, run `service:discover`. ```json "extra": { "think": { "services": [ "think\\captcha\\CaptchaService" ] } }, ``` -------------------------------- ### Define Route with Denied URL Suffixes Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that explicitly denies access with '.jpg', '.png', or '.gif' suffixes. ```php Route::get('new/:id', 'News/read') ->denyExt('jpg|png|gif'); ``` -------------------------------- ### Get Current Application Name Source: https://doc.thinkphp.cn/v6_1/duoyingyongmoshi.html Retrieve the name of the currently active application using the `app('http')->getName()` helper function. ```php app('http')->getName(); ``` -------------------------------- ### Configure Composer with Huawei Cloud Mirror Source: https://doc.thinkphp.cn/v6_1/anzhuangThinkPHP.html Configure Composer to use the Huawei Cloud mirror for faster package downloads. This is recommended due to potential slow speeds from the default Composer repository. ```bash composer config -g repo.packagist composer https://repo.huaweicloud.com/repository/php/ ``` -------------------------------- ### Define User Validator Class Source: https://doc.thinkphp.cn/v6_1/yanzhengqi.html Define a validator class for specific validation scenarios. This example sets up rules for 'name' and 'email'. ```php namespace app\validate; use think\Validate; class User extends Validate { protected $rule = [ 'name' => 'require|max:25', 'email' => 'email', ]; } ``` -------------------------------- ### 批量绑定类库到容器 Source: https://doc.thinkphp.cn/v6_1/rongqiheyilaizhuru.html 在`app`目录下的`provider.php`文件中定义类库绑定,系统会自动批量绑定这些类库到容器。绑定标识区分大小写,核心类库已内置绑定。 ```php return [ 'route' => \think\Route::class, 'session' => \think\Session::class, 'url' => \think\Url::class, ]; ``` -------------------------------- ### Query Builder - Force Index Source: https://doc.thinkphp.cn/v6_1/force.html Demonstrates how to use the `force` method on the query builder to specify a database index for query optimization. ```APIDOC ## POST /api/users ### Description This endpoint demonstrates the usage of the `force` method in the ThinkPHP query builder to enforce the use of a specific database index during a select query. ### Method GET ### Endpoint Db::table('user')->force('user')->select(); ### Parameters #### Query Parameters - **index_name** (string) - Required - The name of the database index to force. ### Request Example ```json { "query": "SELECT * FROM user FORCE INDEX (user)" } ``` ### Response #### Success Response (200) - **data** (array) - The result set from the database query. #### Response Example ```json { "data": [ { "id": 1, "name": "Example User" } ] } ``` ``` -------------------------------- ### Pivot Model with Timestamp Auto-Writing Source: https://doc.thinkphp.cn/v6_1/duoduiduoguanlian.html Example of a pivot model that extends `think\model\Pivot` and enables automatic timestamp writing for the intermediate table. ```php 'mysql', 'connections' => [ 'mysql' => [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'thinkphp', // 数据库用户名 'username' => 'root', // 数据库密码 'password' => '', // 数据库连接端口 'hostport' => '', // 数据库连接参数 'params' => [], // 数据库编码默认采用utf8 'charset' => 'utf8', // 数据库表前缀 'prefix' => 'think_', ], 'demo' => [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'demo', // 数据库用户名 'username' => 'root', // 数据库密码 'password' => '', // 数据库连接端口 'hostport' => '', // 数据库连接参数 'params' => [], // 数据库编码默认采用utf8 'charset' => 'utf8', // 数据库表前缀 'prefix' => 'think_', ], ], ]; ``` -------------------------------- ### Load Custom Configuration File Source: https://doc.thinkphp.cn/v6_1/peizhi.html Manually load a custom configuration file from a subdirectory using the Config facade. The second argument specifies the configuration group name. ```php // Load config/extra/config.php configuration file, read into 'extra' \think\facade\Config::load('extra/config', 'extra'); ``` -------------------------------- ### Get Relationship Sum with withSum Source: https://doc.thinkphp.cn/v6_1/guanliantongji.html Use `withSum` to calculate the sum of a specific field from related records. The result is appended with `_sum` by default. ```php $list = User::withSum('cards', 'total')->select([1,2,3]); foreach($user as $user){ // 获取用户关联的card关联余额统计 echo $user->cards_sum; } ``` -------------------------------- ### Error Access Example Source: https://doc.thinkphp.cn/v6_1/zhujieyanzheng.html Accessing the endpoint without the required 'name' parameter will result in an error, as defined by the 'require' rule in the 'create' scene. ```bash http://127.0.0.1:8000/hello ``` -------------------------------- ### Index Controller with Multiple Methods (ThinkPHP) Source: https://doc.thinkphp.cn/v6_1/jiagouzonglan.html An example of an Index controller with two distinct methods, 'index' and 'hello'. The 'hello' method accepts a string parameter 'name' which is expected to be provided via the request. ```php save($data); ``` -------------------------------- ### Direct Update using Static Method (with conditions) Source: https://doc.thinkphp.cn/v6_1/gengxin.html Use the static `update()` method for direct updates. Provide the data to update as the first argument and the update conditions as the second. ```php User::update(['name' => 'thinkphp'], ['id' => 1]); ``` -------------------------------- ### Updating Facade Usage Source: https://doc.thinkphp.cn/v6_1/shengjizhidao.html System Facade class aliases are removed. Use the fully qualified namespace for Facades. ```PHP use Route; Route::rule('hello/:name', 'index/hello'); ``` ```PHP use think\facade\Route; Route::rule('hello/:name', 'index/hello'); ``` -------------------------------- ### Define Route with Appended Parameters Source: https://doc.thinkphp.cn/v6_1/luyoucanshu.html Defines a GET route that automatically appends 'app_id' with value 1 and 'status' with value 1 to the request parameters. ```php Route::get('blog/:id', 'Blog/read') ->append(['app_id' => 1, 'status' => 1]); ``` -------------------------------- ### Raw SQL Queries with Db Class Source: https://doc.thinkphp.cn/v6_1/yuanshengSQL.html This section covers the `query` and `execute` methods for running raw SQL statements. It also explains parameter binding and behavior with distributed databases. ```APIDOC ## Raw SQL Queries ThinkPHP's `Db` class supports raw SQL query operations, primarily through two methods: `query` and `execute`. **Note:** Starting from v6.0.3, raw queries are only supported via the `Db` class and not within models. ### `query` Method The `query` method is used to execute SQL SELECT statements and returns the query results as a dataset (array). **Usage Example:** ```php Db::query("select * from think_user where status=:id", ['id' => 1]); ``` **Behavior with Distributed Databases:** If you are using a distributed database with read/write separation, the `query` method defaults to executing on the read server, regardless of the SQL statement. To force execution on the primary server, use the third parameter: ```php Db::query("select * from think_user where status=:id", ['id' => 1], true); ``` ### `execute` Method The `execute` method is used for SQL operations that modify data (INSERT, UPDATE, DELETE). It returns `false` if the data is invalid or the query fails, otherwise, it returns the number of affected rows. **Usage Example:** ```php Db::execute("update think_user set name='thinkphp' where status=1"); ``` **Behavior with Distributed Databases:** If you are using a distributed database with read/write separation, the `execute` method always executes on the write server. ### Parameter Binding Parameter binding is supported for raw queries using either question mark placeholders or named placeholders. **Example with Question Mark Placeholders:** ```php Db::query("select * from think_user where id=? AND status=?", [8, 1]); ``` **Example with Named Placeholders:** ```php Db::execute("update think_user set name=:name where status=:status", ['name' => 'thinkphp', 'status' => 1]); ``` **Note:** Parameter binding is not supported for table names. ``` -------------------------------- ### Route to Class Method Source: https://doc.thinkphp.cn/v6_1/luyoudizhi.html Routes a GET request to a specific method within a class. Supports both instance methods (using '@') and static methods (using '::'). ```PHP Route::get('blog/:id','\app\index\service\Blog@read'); ``` ```PHP Route::get('blog/:id','\app\index\service\Blog::read'); ``` -------------------------------- ### Query Builder - Procedure Source: https://doc.thinkphp.cn/v6_1/procedure.html Demonstrates how to use the `procedure` method in the Query Builder to execute stored procedures. ```APIDOC ## Procedure Query ### Description The `procedure` method is used to set the current query as a stored procedure query. This is useful when you need to execute stored procedures within your application. ### Method This method is part of the Query Builder chain. ### Endpoint N/A (This is a Query Builder method, not an API endpoint.) ### Parameters #### Query Builder Method - **procedure**(boolean) - Required - `true` to indicate a stored procedure query. ### Request Example ```php query('call procedure_name'); ?> ``` ### Response #### Success Response (200) - **resultSet** (object) - The result set returned by the stored procedure. #### Response Example (The structure of the response depends on the stored procedure's output.) ``` -------------------------------- ### Validate using filter_var Source: https://doc.thinkphp.cn/v6_1/neizhiguize.html Leverage PHP's built-in `filter_var` function for validation by specifying the filter name. Example: 'ip'=>'filter:validate_ip'. ```php 'ip'=>'filter:validate_ip' ``` -------------------------------- ### Generate URL with Entry File Source: https://doc.thinkphp.cn/v6_1/URLshengcheng.html Use Route::buildUrl with the root method to specify the entry file (e.g., index.php) in the generated URL. ```php Route::buildUrl('index/blog/read', ['id'=>5])->root('/index.php'); ``` -------------------------------- ### 使用app助手函数解析容器类 Source: https://doc.thinkphp.cn/v6_1/rongqiheyilaizhuru.html 使用`app('标识')`解析容器中已绑定的类。对于未绑定的类,也可以直接解析。调用和绑定的标识必须保持一致(包括大小写)。 ```php $cache = app('cache'); ``` ```php $cache = app('cache',['file']); ``` ```php $arrayItem = app('org\utils\ArrayItem'); ``` -------------------------------- ### Validate Date Before a Specific Date Source: https://doc.thinkphp.cn/v6_1/neizhiguize.html The 'before' rule verifies if a date field's value is earlier than a specified date. Example: 'end_time' => 'before:2016-10-01'. ```php 'end_time' => 'before:2016-10-01' ``` -------------------------------- ### Validate Date After a Specific Date Source: https://doc.thinkphp.cn/v6_1/neizhiguize.html The 'after' rule checks if a date field's value is later than a specified date. Example: 'begin_time' => 'after:2016-3-18'. ```php 'begin_time' => 'after:2016-3-18' ``` -------------------------------- ### Configure Console Output Source: https://doc.thinkphp.cn/v6_1/yemianTrace.html Enable Trace functionality to output debugging information directly to the browser's console by setting the 'type' parameter to 'console' in the configuration. ```php // 使用浏览器console输出trace信息 'type' => 'console', ``` -------------------------------- ### Get PARAM Parameters using input() Source: https://doc.thinkphp.cn/v6_1/shurubianliang.html Retrieve single or all PARAM parameters using the `input()` function. If no type is specified, it defaults to retrieving PARAM variables. ```php input('param.name'); ``` ```php input('param.'); ``` ```php input('name'); ``` ```php input(''); ``` -------------------------------- ### Get Specific Request Variables Source: https://doc.thinkphp.cn/v6_1/shurubianliang.html Use the `only` method to safely retrieve specific variables from the current request. This prevents unexpected variables from affecting data processing. ```php Request::only(['id','name']); ``` -------------------------------- ### 配置默认语言 Source: https://doc.thinkphp.cn/v6_1/duoyuyan.html 在`lang.php`配置文件中设置`default_lang`参数来指定默认语言。 ```php // 默认语言 'default_lang' => 'zh-cn', ```