1. Go to this page and download the library: Download yangweijie/think-orm-async library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
yangweijie / think-orm-async example snippets
namespace app\model;
use think\Model;
use Yangweijie\ThinkOrmAsync\AsyncModelTrait;
class User extends Model {
use AsyncModelTrait;
protected $name = 'user';
protected $prefix = ''; // 可选:表前缀
}
class Order extends Model {
use AsyncModelTrait;
protected $name = 'order';
}
class Product extends Model {
use AsyncModelTrait;
protected $name = 'product';
}
namespace app\controller;
use Yangweijie\ThinkOrmAsync\AsyncContext;
use app\model\User;
use app\model\Order;
use app\model\Product;
class UserController {
public function detail($id) {
// 开始异步上下文(自动从配置读取数据库配置)
AsyncContext::start();
// ORM 查询
$user = User::where('id', $id)->find();
$orders = Order::where('user_id', $id)->select();
$products = Product::where('status', 1)->select();
// 原生 SQL 查询
$stats = AsyncContext::query("SELECT COUNT(*) as total FROM user");
// 结束异步上下文,执行所有查询(并行执行)
AsyncContext::end();
// 使用结果(和同步模式完全一样)
echo $user->name;
foreach ($orders as $order) {
echo $order->order_no;
}
echo "Products: " . count($products);
echo "Total users: " . $stats[0]['total'];
}
}
AsyncContext::start();
// 简单查询
$result = AsyncContext::query("SELECT * FROM user WHERE id = 1");
// 复杂查询
$stats = AsyncContext::query("
SELECT
COUNT(*) as total,
AVG(age) as avg_age
FROM user
WHERE status = 1
");
// 自定义 key
$custom = AsyncContext::query("SELECT COUNT(*) FROM order", 'order_count');
$results = AsyncContext::end();
// 访问结果
echo $result[0]['name'];
echo $stats[0]['total'];
echo $custom[0]['order_count'];
AsyncContext::start();
// ORM 查询
$user = User::find(1);
$orders = Order::where('user_id', 1)->select();
// 原生查询
$stats = AsyncContext::query("SELECT COUNT(*) as total FROM user");
$results = AsyncContext::end();
// 所有查询并行执行