PHP code example of easyswoole / fast-db

1. Go to this page and download the library: Download easyswoole/fast-db 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/ */

    

easyswoole / fast-db example snippets




namespace EasySwoole\EasySwoole;

use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\FastDb\FastDb;

class EasySwooleEvent implements Event
{
    public static function initialize()
    {
        date_default_timezone_set('Asia/Shanghai');

        // 注册方式1:在 initialize 方法中注册连接
        $config = new \EasySwoole\FastDb\Config([
            'name'              => 'default',    // 设置 连接池名称,默认为 default
            'host'              => '127.0.0.1',  // 设置 数据库 host
            'user'              => 'easyswoole', // 设置 数据库 用户名
            'password'          => 'easyswoole', // 设置 数据库 用户密码
            'database'          => 'easyswoole', // 设置 数据库库名
            'port'              => 3306,         // 设置 数据库 端口
            'timeout'           => 5,            // 设置 数据库连接超时时间
            'charset'           => 'utf8',       // 设置 数据库字符编码,默认为 utf8
            'autoPing'          => 5,            // 设置 自动 ping 客户端链接的间隔
            'useMysqli'         => false,        // 设置 不使用 php mysqli 扩展连接数据库
            // 配置 数据库 连接池配置,配置详细说明请看连接池组件 https://www.easyswoole.com/Components/Pool/introduction.html
            // 下面的参数可使用组件提供的默认值
            'intervalCheckTime' => 15 * 1000,    // 设置 连接池定时器执行频率
            'maxIdleTime'       => 10,           // 设置 连接池对象最大闲置时间 (秒)
            'maxObjectNum'      => 20,           // 设置 连接池最大数量
            'minObjectNum'      => 5,            // 设置 连接池最小数量
            'getObjectTimeout'  => 3.0,          // 设置 获取连接池的超时时间
            'loadAverageTime'   => 0.001,        // 设置 负载阈值
        ]);
        // 或使用对象设置属性方式进行配置
        // $config->setName('default');
        // $config->setHost('127.0.0.1');
        FastDb::getInstance()->addDb($config);
        // 或在注册时指定连接池的名称
        // FastDb::getInstance()->addDb($config, $config['name']);
    }

    public static function mainServerCreate(EventRegister $register)
    {
        // 注册方式2:在 mainServerCreate 方法中注册连接
//        $config = new \EasySwoole\FastDb\Config([
//            'name'              => 'default',    // 设置 连接池名称,默认为 default
//            'host'              => '127.0.0.1',  // 设置 数据库 host
//            'user'              => 'easyswoole', // 设置 数据库 用户名
//            'password'          => 'easyswoole', // 设置 数据库 用户密码
//            'database'          => 'easyswoole', // 设置 数据库库名
//            'port'              => 3306,         // 设置 数据库 端口
//            'timeout'           => 5,            // 设置 数据库连接超时时间
//            'charset'           => 'utf8',       // 设置 数据库字符编码,默认为 utf8
//            'autoPing'          => 5,            // 设置 自动 ping 客户端链接的间隔
//            // 配置 数据库 连接池配置,配置详细说明请看连接池组件 https://www.easyswoole.com/Components/Pool/introduction.html
//            // 下面的参数可使用组件提供的默认值
//            'intervalCheckTime' => 15 * 1000,    // 设置 连接池定时器执行频率
//            'maxIdleTime'       => 10,           // 设置 连接池对象最大闲置时间 (秒)
//            'maxObjectNum'      => 20,           // 设置 连接池最大数量
//            'minObjectNum'      => 5,            // 设置 连接池最小数量
//            'getObjectTimeout'  => 3.0,          // 设置 获取连接池的超时时间
//            'loadAverageTime'   => 0.001,        // 设置 负载阈值
//        ]);
//        FastDb::getInstance()->addDb($config);
    }
}


use EasySwoole\FastDb\FastDb;
$config = new \EasySwoole\FastDb\Config([
    'name'              => 'default',    // 设置 连接池名称,默认为 default
    'host'              => '127.0.0.1',  // 设置 数据库 host
    'user'              => 'easyswoole', // 设置 数据库 用户名
    'password'          => 'easyswoole', // 设置 数据库 用户密码
    'database'          => 'easyswoole', // 设置 数据库库名
    'port'              => 3306,         // 设置 数据库 端口
    'timeout'           => 5,            // 设置 数据库连接超时时间
    'charset'           => 'utf8',       // 设置 数据库字符编码,默认为 utf8
    'autoPing'          => 5,            // 设置 自动 ping 客户端链接的间隔
    'useMysqli'         => false,        // 设置 不使用 php mysqli 扩展连接数据库
    // 配置 数据库 连接池配置,配置详细说明请看连接池组件 https://www.easyswoole.com/Components/Pool/introduction.html
    // 下面的参数可使用组件提供的默认值
    'intervalCheckTime' => 15 * 1000,    // 设置 连接池定时器执行频率
    'maxIdleTime'       => 10,           // 设置 连接池对象最大闲置时间 (秒)
    'maxObjectNum'      => 20,           // 设置 连接池最大数量
    'minObjectNum'      => 5,            // 设置 连接池最小数量
    'getObjectTimeout'  => 3.0,          // 设置 获取连接池的超时时间
    'loadAverageTime'   => 0.001,        // 设置 负载阈值
]);
FastDb::getInstance()->addDb($config);


declare(strict_types=1);

namespace App\Model;

use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;

/**
 * @property int $id increment id
 * @property string|null $name name
 * @property int|null $status status
 * @property int|null $score score
 * @property int|null $sex sex
 * @property string|null $address address
 * @property string|null $email email
 */
class EasySwooleUser extends AbstractEntity
{
    #[Property(isPrimaryKey: true)]
    public int $id;
    #[Property]
    public ?string $name;
    #[Property]
    public ?int $status;
    #[Property]
    public ?int $score;
    #[Property]
    public ?int $sex;
    #[Property]
    public ?string $address;
    #[Property]
    public ?string $email;

    public function tableName(): string
    {
        return 'easyswoole_user';
    }
}


// bootstrap.php
// 全局bootstrap事件
date_default_timezone_set('Asia/Shanghai');

$argvArr = $argv;
array_shift($argvArr);
$command = $argvArr[0] ?? null;
if ($command === 'model') {
    \EasySwoole\EasySwoole\Core::getInstance()->initialize();
}
\EasySwoole\Command\CommandManager::getInstance()->addCommand(new \EasySwoole\FastDb\Commands\ModelCommand());



declare(strict_types=1);

namespace App\Model;

use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;

/**
 * @property int $id
 * @property string|null $name
 * @property int|null $status
 * @property int|null $score
 * @property int|null $sex
 * @property string|null $address
 * @property string|null $email
 */
class EasyswooleUser extends AbstractEntity
{
    #[Property(isPrimaryKey: true)]
    public int $id;
    #[Property]
    public ?string $name;
    #[Property]
    public ?int $status;
    #[Property]
    public ?int $score;
    #[Property]
    public ?int $sex;
    #[Property]
    public ?string $address;
    #[Property]
    public ?string $email;

    public function tableName(): string
    {
        return 'easyswoole_user';
    }
}


$user = new User();
$user->name = 'easyswoole';
$user->email = '[email protected]';
$user->insert();
// 相当于 sql: INSERT  INTO `easyswoole_user` (`name`, `email`)  VALUES ('easyswoole', '[email protected]')


$user = new User();
$user->setData([
    'name'  => 'easyswoole',
    'email' => '[email protected]'
]);
$user->insert();


$user = new User([
    'name'  => 'easyswoole',
    'email' => '[email protected]'
]);
$user->insert();


$user = new User();
$user->name = 'easyswoole';
$user->email = '[email protected]';
$user->insert();
// 获取自增ID
echo $user->id;


$user = new User();
$user->name = 'easyswoole';
$user->email = '[email protected]';
$user->insert();
// 获取自增ID
echo $user->user_id;


$user = new User();
$list = [
    ['name' => 'easyswoole-1', 'email' => '[email protected]'],
    ['name' => 'easyswoole-2', 'email' => '[email protected]']
];
$user->insertAll($list); // 结果为 对象数组

$user = new User();
$list = [
    ['name' => 'easyswoole-1', 'email' => '[email protected]'],
    ['name' => 'easyswoole-2', 'email' => '[email protected]']
];
$user->queryLimit()->fields(null, true);
$user->insertAll($list); // 结果为 普通数组


$user = new User;
$list = [
    ['id' => 1, 'name' => 'easyswoole-1', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'easyswoole-2', 'email' => '[email protected]']
];
$user->insertAll($list, false);



declare(strict_types=1);

namespace App\Model;

use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Hook\OnInsert;
// ...

/**
 * @property int    $id
 * @property string $name
 * @property int    $status
 * @property int    $create_time
 * @property string $email
 */
#[OnInsert('onInsert')]
class User extends AbstractEntity
{
    // ...
    
    public function onInsert()
    {
        if (empty($this->create_time)) {
            $this->create_time = time();
        }
        if (empty($this->status)) {
            $this->status = 1;
        }
    }
}


$user = new User();
$user->name = 'easyswoole';
$user->email = '[email protected]';
$user->insert(); // INSERT  INTO `easyswoole_user` (`name`, `status`, `create_time`, `email`)  VALUES ('easyswoole', 1, 1704521166, '[email protected]')


$user = new User();
$user->name = 'easyswoole100';
$updateDuplicateCols = ['name'];
$user->insert($updateDuplicateCols); // INSERT  INTO `easyswoole_user` (`name`, `status`, `create_time`)  VALUES ('easyswoole100', 1, 1704521621) ON DUPLICATE KEY UPDATE `name` = 'easyswoole100'

$user = new User();
$user->name = 'easyswoole100';
$updateDuplicateCols = ['name', 'id' => 1];
$user->insert($updateDuplicateCols); // INSERT  INTO `easyswoole_user` (`name`, `status`, `create_time`)  VALUES ('easyswoole100', 1, 1704521622) ON DUPLICATE KEY UPDATE `id` = 1, `name` = 'easyswoole100'


$user = User::findRecord(1);
$user->name = 'easyswoole111';
$user->email = '[email protected]';
$user->update();

$user = new User();
// updateWithLimit 方法第二个参数为更新条件
$user->updateWithLimit([
    'name'  => 'easyswoole112',
    'email' => '[email protected]'
], ['id' => 1]);

// 调用静态方法
User::fastUpdate(['id' => 1], [
    'name'  => 'easyswoole112',
    'email' => '[email protected]'
]);

User::fastUpdate(function (\EasySwoole\Mysqli\QueryBuilder $queryBuilder) {
  $queryBuilder->where('id', 1);
}, [
    'name'  => 'easyswoole112',
    'email' => '[email protected]'
]);

User::fastUpdate(1, [
    'name'  => 'easyswoole112',
    'email' => '[email protected]'
]);

User::fastUpdate('1,2', [
    'name'  => 'easyswoole112',
    'email' => '[email protected]'
]);


$user = new User();
$user->queryLimit()->where('id', 1);
$user->updateWithLimit(['name' => 'easyswoole']);


$user = new User();
$user->updateWithLimit(['name' => 'easyswoole'], function (\EasySwoole\FastDb\Beans\Query $query) {
    // 更新status值为1 并且id大于10的数据
    $query->where('status', 1)->where('id', 10, '>');
}); // UPDATE `easyswoole_user` SET `name` = 'easyswoole' WHERE  `status` = 1  AND `id` > 10


$user = User::findRecord(1);
$user->delete();

User::fastDelete(1);
// 支持批量删除多个数据
User::fastDelete('1,2,3');


// 删除状态为0的数据
User::fastDelete(['status' => 0]);


User::fastDelete(function (\EasySwoole\Mysqli\QueryBuilder $query) {
    $query->where('id', 10, '>');
});


// 取出主键为1的数据
$user = User::findRecord(1);
echo $user->name;

// 使用数组查询
$user = User::findRecord(['name' => 'easyswoole']);
echo $user->name;

// 使用闭包查询
$user = User::findRecord(function (\EasySwoole\Mysqli\QueryBuilder $query) {
    $query->where('name', 'easyswoole');
});
echo $user->name;

$user = new User();
// 查询单个数据
$user->qyeryLimit()->where('name', 'easyswoole');
$userModel = $user->find();
echo $userModel->name;


// 使用主键查询
$list = User::findAll('1,2');

// 使用数组查询
$list = User::findAll(['status' => 1]);

// 使用闭包查询
$list = User::findAll(function (\EasySwoole\Mysqli\QueryBuilder $query) {
    $query->where('status', 1)->limit(3)->orderBy('id', 'asc');
}, null, false);
foreach ($list as $key => $user) {
    echo $user->name;
}


// 获取多个数据 不使用条件查询
/** @var User[] $users */
$users = (new User())->all(); // 返回结果:\EasySwoole\FastDb\Beans\ListResult 类的对象
foreach ($users as $user) {
    echo $user->name . "\n";
}

// 获取多个数据 使用条件查询(闭包条件)
$userModel = new User();
$userModel->queryLimit()->where('id', [401, 403], 'IN')->where('name', 'easyswoole-1');
$users = $userModel->all(); // 返回结果:\EasySwoole\FastDb\Beans\ListResult 类的对象
foreach ($users as $user) {
    echo $user->name . "\n";
}

CREATE TABLE `student_info` (
  `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  `studentId` int unsigned NOT NULL DEFAULT '0' COMMENT 'student id',
  `address` json DEFAULT NULL COMMENT 'address',
  `note` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'note',
  `sex` tinyint unsigned NOT NULL DEFAULT '0' COMMENT 'sex:1=male 2=female 0=unknown',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;


namespace EasySwoole\FastDb\Tests\Model;

use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;
use EasySwoole\FastDb\Tests\Model\Address;
use EasySwoole\FastDb\Tests\Model\SexEnum;

class StudentInfoModel extends AbstractEntity
{
    #[Property(isPrimaryKey: true)]
    public int $id;

    #[Property()]
    public int $studentId;

    #[Property(
        convertObject: Address::class
    )]
    public Address $address;

    #[Property]
    public ?string $note;

    #[Property(
        convertObject: SexEnum::class
    )]
    public SexEnum $sex;

    function tableName(): string
    {
        return "student_info";
    }
}


namespace EasySwoole\FastDb\Tests\Model;

use EasySwoole\FastDb\AbstractInterface\ConvertJson;

class Address extends ConvertJson
{
    public $city;
    public $province;
}


namespace EasySwoole\FastDb\Tests\Model;

use EasySwoole\FastDb\AbstractInterface\ConvertObjectInterface;

enum SexEnum implements ConvertObjectInterface
{
    case UNKNUWN;
    case MALE;
    case FEMAILE;

    public static function toObject(mixed $data): object
    {
        switch ($data){
            case 1:{
                return self::MALE;
            }
            case 2:{
                return self::FEMAILE;
            }
            default:{
                return self::UNKNUWN;
            }
        }
    }

    function toValue()
    {
        return match ($this){
            self::MALE=>1,
            self::FEMAILE=>2,
            default=>0
        };
    }
}


// 添加记录
$address = new \EasySwoole\FastDb\Tests\Model\Address();
$address->province = 'FuJian';
$address->city = 'XiaMen';
$sex = \EasySwoole\FastDb\Tests\Model\SexEnum::MALE;
$model = new StudentInfoModel([
    'studentId' => 1,
    'address'   => $address->toValue(),
    'sex'       => $sex->toValue(),
    'note'      => 'this is note',
]);
// or
// $model->address = $address;
// $model->sex = $sex;
$model->insert(); // INSERT  INTO `student_info` (`studentId`, `address`, `note`, `sex`)  VALUES (1, '{\"city\":\"XiaMen\",\"province\":\"FuJian\"}', 'this is note', 1)

// 查询一条数据
$studentInfo = StudentInfoModel::findRecord(1);
var_dump($studentInfo->address->city); // "XiaMen"
var_dump($studentInfo->address->province); // "FuJian"
var_dump($studentInfo->sex); // 枚举类型 enum(EasySwoole\FastDb\Tests\Model\SexEnum::MALE)
var_dump($studentInfo->toArray(false));

// 查询多条数据
$studentInfo = new StudentInfoModel();
$studentInfos = $studentInfo->all();
foreach ($studentInfos as $studentInfo) {
    var_dump($studentInfo->address->city);
    var_dump($studentInfo->address->province);
    var_dump($studentInfo->sex);
    var_dump($studentInfo->toArray(false));
}


$returnAsArray = true;
(new User())->findAll(null, null, $returnAsArray);


$returnAsArray = true;
(new User())->queryLimit()->fields(null, $returnAsArray);


(new User())->chunk(function (User $user) {
    // 处理 user 模型对象
    $user->updateWithLimit(['status' => 1]);
}, 20);

function page(?int $page,bool $withTotalCount = false,int $pageSize = 10): Query

// 使用条件的分页查询 不进行汇总 withTotalCount=false
// 查询 第1页 每页10条 page=1 pageSize=10
$user = new User();
$user->queryLimit()->page(1, false, 10);
$resultObject = $user->all();
foreach ($resultObject as $oneUser) {
    var_dump($oneUser->name);
}

// 使用条件的分页查询 进行汇总 withTotalCount=true
// 查询 第1页 每页10条 page=1 pageSize=10
$user = new User();
$user->queryLimit()->page(1, true, 10)->where('id', 3, '>');
$resultObject = $user->all();
$total = $resultObject->totalCount(); // 汇总数量
foreach ($resultObject as $oneUser) {
    var_dump($oneUser->name);
}
var_dump($total);


$user = new User();
$user->count();
// SELECT  COUNT(*) as count FROM `easyswoole_user` LIMIT 1

$user->count('id', 'name');
// SELECT  COUNT(id) as count FROM `easyswoole_user` GROUP BY name  LIMIT 1

$user->queryLimit()->fields(['id', 'name']);
$user->count(null, 'name');
// SELECT  COUNT(`id`) as id, COUNT(`name`) as name FROM `easyswoole_user` GROUP BY name  LIMIT 1

$user = new User();
$user->max('id');
// SELECT  MAX(`id`) as id FROM `easyswoole_user` LIMIT 1

$user->max('id', 'name');
// SELECT  MAX(`id`) as id FROM `easyswoole_user` GROUP BY name  LIMIT 1

$user->max(['id', 'name'], 'name');
// SELECT  MAX(`id`) as id , MAX(`name`) as name FROM `easyswoole_user` GROUP BY name  LIMIT 1


$user = new User();
$user->min('id');
// SELECT  MIN(`id`) as id FROM `easyswoole_user` LIMIT 1

$user->min('id', 'name');
// SELECT  MIN(`id`) as id FROM `easyswoole_user` GROUP BY name  LIMIT 1

$user->min(['id', 'name'], 'name');
// SELECT  MIN(`id`) as id , MIN(`name`) as name FROM `easyswoole_user` GROUP BY name  LIMIT 1


$user = new User();
$user->avg('id');
// SELECT  AVG(`id`) as id FROM `easyswoole_user` LIMIT 1

$user->avg('id', 'name');
// SELECT  AVG(`id`) as id FROM `easyswoole_user` GROUP BY name  LIMIT 1

$user->avg(['id', 'name'], 'name');
// SELECT  AVG(`id`) as id , AVG(`name`) as name FROM `easyswoole_user` GROUP BY name  LIMIT 1


$user = new User();
$user->sum('id');
// SELECT  SUM(`id`) as id FROM `easyswoole_user` LIMIT 1

$user->sum('id', 'name');
// SELECT  SUM(`id`) as id FROM `easyswoole_user` GROUP BY name  LIMIT 1

$user->sum(['id', 'name'], 'name');
// SELECT  SUM(`id`) as id , SUM(`name`) as name FROM `easyswoole_user` GROUP BY name  LIMIT 1


$user = User::findRecord(1);
var_dump($user->toArray(false));

/** @var \EasySwoole\FastDb\Beans\ListResult $listResult */
$listResult = (new User)->all();
$objectArr = $listResult->toArray(); // 转换为 对象数组


declare(strict_types=1);

namespace EasySwoole\FastDb\Tests\Model;

use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Hook\OnInitialize;
use EasySwoole\FastDb\Attributes\Hook\OnInsert;
use EasySwoole\FastDb\Attributes\Hook\OnDelete;
use EasySwoole\FastDb\Attributes\Hook\OnUpdate;
// ...

/**
 * @property int    $id
 * @property string $name
 * @property int    $status
 * @property int    $score
 * @property int    $create_time
 */
#[OnInitialize('onInitialize')]
#[OnInsert('onInsert')]
#[OnDelete('onDelete')]
#[OnUpdate('onUpdate')]
class User extends AbstractEntity
{
    // ...
    
    public function onInitialize()
    {
        // todo::
    }

    public function onInsert()
    {
        if (empty($this->status)) {
            return false;
        }
        if (empty($this->create_time)) {
            $this->create_time = time();
        }
    }

    public function onDelete()
    {
        // todo::
    }

    public function onUpdate()
    {
        // todo::
    }
}

$user = new User(['name' => 'EasySwoole', 'id' => 1000]);
$result = $user->insert();
var_dump($result); // false,返回 false,表示 insert 失败。


declare(strict_types=1);

namespace EasySwoole\FastDb\Tests\Model;

use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;
use EasySwoole\FastDb\Attributes\Relate;
use EasySwoole\FastDb\Tests\Model\UserProfile;

/**
 * @property int    $id
 * @property string $name
 * @property string $email
 */
class User extends AbstractEntity
{
    #[Property(isPrimaryKey: true)]
    public int $id;
    #[Property]
    public ?string $name;
    #[Property]
    public ?string $email;

    public function tableName(): string
    {
        return 'easyswoole_user';
    }

    #[Relate(
        targetEntity: UserProfile::class,
        targetProperty: 'user_id' // 关联模型的数据表的主键
    )]
    public function profile()
    {
        return $this->relateOne();
    }
}


$user = User::findRecord(1);
// 输出 UserProfile 关联模型的email属性
echo $user->profile()->email;


declare(strict_types=1);

namespace EasySwoole\FastDb\Tests\Model;

use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;
use EasySwoole\FastDb\Attributes\Relate;
use EasySwoole\FastDb\Tests\Model\UserCar;

/**
 * @property int    $id
 * @property string $name
 * @property int    $status
 * @property int    $score
 * @property string $email
 */
class User extends AbstractEntity
{
    #[Property(isPrimaryKey: true)]
    public int $id;
    #[Property]
    public ?string $name;
    #[Property]
    public ?int $status;
    #[Property]
    public ?int $score;
    #[Property]
    public ?int $create_time;
    #[Property]
    public ?string $info;
    #[Property]
    public ?string $foo;
    #[Property]
    public ?string $bar;
    #[Property]
    public ?int $login_time;
    #[Property]
    public ?int $login_times;
    #[Property]
    public ?int $read;
    #[Property]
    public ?string $title;
    #[Property]
    public ?string $content;
    #[Property]
    public ?string $email;

    public function tableName(): string
    {
        return 'easyswoole_user';
    }
    
    #[Relate(
        targetEntity: UserCar::class,
        targetProperty: 'user_id'
    )]
    public function cars()
    {
        return $this->relateMany();
    }
}


$article = User::findRecord(1);
// 获取用户拥有的所有车辆品牌
$listResult = $article->cars();
foreach ($listResult as $userCar) {
    echo $userCar->car_name . "\n";
}
// or
$objectArr = $listResult->toArray(); // 转换为 对象数组
foreach ($objectArr as $userCar) {
    echo $userCar->car_name . "\n";
}


$config = new \EasySwoole\FastDb\Config([
    'name'              => 'default',    // 设置 连接池名称,默认为 default
    'host'              => '127.0.0.1',  // 设置 数据库 host
    'user'              => 'easyswoole', // 设置 数据库 用户名
    'password'          => 'easyswoole', // 设置 数据库 用户密码
    'database'          => 'easyswoole', // 设置 数据库库名
    'port'              => 3306,         // 设置 数据库 端口
    'timeout'           => 5,            // 设置 数据库连接超时时间
    'charset'           => 'utf8',       // 设置 数据库字符编码,默认为 utf8
    'autoPing'          => 5,            // 设置 自动 ping 客户端链接的间隔
    'useMysqli'         => false,        // 设置 不使用 php mysqli 扩展连接数据库
    // 配置 数据库 连接池配置,配置详细说明请看连接池组件 https://www.easyswoole.com/Components/Pool/introduction.html
    // 下面的参数可使用组件提供的默认值
    'intervalCheckTime' => 15 * 1000,    // 设置 连接池定时器执行频率
    'maxIdleTime'       => 10,           // 设置 连接池对象最大闲置时间 (秒)
    'maxObjectNum'      => 20,           // 设置 连接池最大数量
    'minObjectNum'      => 5,            // 设置 连接池最小数量
    'getObjectTimeout'  => 3.0,          // 设置 获取连接池的超时时间
    'loadAverageTime'   => 0.001,        // 设置 负载阈值
]);
// 或使用对象设置属性方式进行配置
// $config->setName('default');
// $config->setHost('127.0.0.1');
FastDb::getInstance()->addDb($config);

FastDb::getInstance()->testDb();
FastDb::getInstance()->testDb('read');
FastDb::getInstance()->testDb('write');


FastDb::getInstance()->setOnQuery(function (\asySwoole\FastDb\Mysql\QueryResult $queryResult) {
    // 打印 sql
    if ($queryResult->getQueryBuilder()) {
        echo $queryResult->getQueryBuilder()->getLastQuery() . "\n";
    } else {
        echo $queryResult->getRawSql() . "\n";
    }
});


$builder = new \EasySwoole\Mysqli\QueryBuilder();
$builder->raw('select * from user');
$result = FastDb::getInstance()->invoke(function (\EasySwoole\FastDb\Mysql\Connection $connection) use ($builder) {
    $connection->query($builder);
    return $connection->rawQuery("select * from user");
});

FastDb::getInstance()->begin();

FastDb::getInstance()->commit();

FastDb::getInstance()->rollback();

$builder = new \EasySwoole\Mysqli\QueryBuilder();
$builder->raw("select * from user where id = ?", [1]);
FastDb::getInstance()->query($builder);

FastDb::getInstance()->rawQuery('select * from user where id = 1');

FastDb::getInstance()->currentConnection();

FastDb::getInstance()->reset();



namespace EasySwoole\EasySwoole;

use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\FastDb\FastDb;

class EasySwooleEvent implements Event
{
    public static function initialize()
    {
        date_default_timezone_set('Asia/Shanghai');

        $mysqlArrayConfig = Config::getInstance()->getConf('MYSQL');
        $config = new \EasySwoole\FastDb\Config($mysqlArrayConfig);
        FastDb::getInstance()->addDb($config);
    }

    public static function mainServerCreate(EventRegister $register)
    {
        $register->add($register::onWorkerStart, function () {
            // 连接预热
            FastDb::getInstance()->preConnect();
        });
    }
}

FastDb::getInstance()->isInTransaction();

FastDb::getInstance()->getConfig();
FastDb::getInstance()->getConfig('read');


try {
    // 启动事务
    FastDb::getInstance()->begin();
    $user = User::findRecord(1000);
    $user->delete();
    // 提交事务
    FastDb::getInstance()->commit();
} catch (\Throwable $throwable) {
    // 回滚事务
    FastDb::getInstance()->rollback();
}

// 或者使用 `invoke` 方法
FastDb::getInstance()->invoke(function (\EasySwoole\FastDb\Mysql\Connection $connection) {
    try {
        // 启动事务
        FastDb::getInstance()->begin($connection);
        $user = User::findRecord(1000);
        $user->delete();
        // 提交事务
        FastDb::getInstance()->commit($connection);
    } catch (\Throwable $throwable) {
        // 回滚事务
        FastDb::getInstance()->rollback($connection);
    }

    return true;
});


$config = new \EasySwoole\FastDb\Config();
$config->setHost('127.0.0.1');
$config->setUser('easyswoole');
$config->setPassword('');
$config->setDatabase('easyswoole');
$config->setName('default');
FastDb::getInstance()->addDb($config);


// 设置 onQuery 回调函数
FastDb::getInstance()->setOnQuery(function (\asySwoole\FastDb\Mysql\QueryResult $queryResult) {
   // 打印 sql
    if ($queryResult->getQueryBuilder()) {
        echo $queryResult->getQueryBuilder()->getLastQuery() . "\n";
    } else {
        echo $queryResult->getRawSql() . "\n";
    }
});

$result = FastDb::getInstance()->rawQuery('call sp_query(8)');

php easyswoole.php model gen -table={table_name}
bash
php easyswoole.php model gen -table=easyswoole_user -with-comments