PHPackages                             swoft-laravel-x1024/database2 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. swoft-laravel-x1024/database2

ActiveLibrary[Database &amp; ORM](/categories/database)

swoft-laravel-x1024/database2
=============================

laravel orm database in swoft

v2.0(6y ago)02MITPHP

Since Jun 10Pushed 6y agoCompare

[ Source](https://github.com/872409/swoft-laravel-database2)[ Packagist](https://packagist.org/packages/swoft-laravel-x1024/database2)[ RSS](/packages/swoft-laravel-x1024-database2/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (1)Dependencies (3)Versions (7)Used By (0)

swoft-laravel-x1024/database2
=============================

[](#swoft-laravel-x1024database2)

集成 laravel orm 组件至 swoft

forked from [swoft-laravel-database](https://github.com/RiceWong/swoft-laravel-database)

php &gt;7.2, swoole &gt; 4.0.3, swoft &gt; v2.x

技术细节
----

[](#技术细节)

1. 技术目标：
    - 独立使用 laravel database, 文档和使用方式参考lavarl 社区文档
    - 在不扩大代码量的情况下，尽可能地迁移 laravel database 的功能: QueryBuilder, Model, ORM, 配置项
    - 支持swoole Coroutine\\MySQL 异步客户端
    - **支持coroutine mysql连接池**
2. 实现
    - 代码部分主要参照 [官方文档](https://github.com/illuminate/database) ，在它的基础之上，整合laravel database数据库配置加载方式
    - 参考 database 本身的mysql driver实现，对Coroutine\\MySQL的相关调用做了一层代理封装, 使其可以与复用mysql driver部分的代码

安装
--

[](#安装)

在composer.json require 中添加如依赖

```
...
    "require": {
        ...
        "swoft-laravel-x1024/database2": "^2.0"
        ...
    }
....
```

更新依赖

```
# 更新所有依赖
composer update
# 或者只更新生产环境依赖
composer update --no-dev
```

在根目录下新建文件 config\\database.php

```
return [
    // 默认连接
    'default' => env('DB_CONNECTION', 'mysql'),
    'connections' => [
        'default' => [
            // 数据库驱动, comysql 为异步客户端
            'driver'    => 'comysql',
            'host'      => env('DB_HOST', '127.0.0.1'),
            'port'      => env('DB_PORT', '3306'),
            'database'  => env('DB_DATABASE', 'your database'),
            'username'  => env('DB_USERNAME', 'you user'),
            'password'  => env('DB_PASSWORD', 'your password'),
            'charset'   => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix'    => 'your table prefix',
            'strict'    => true,
            'engine'    => null,
        ],
        'other' => [
            // 数据库驱动, comysql 为异步客户端
            'driver'    => 'comysql',
            'host'      => env('DB_HOST', '127.0.0.1'),
            'port'      => env('DB_PORT', '3306'),
            'database'  => env('DB_DATABASE', 'your database'),
            'username'  => env('DB_USERNAME', 'you user'),
            'password'  => env('DB_PASSWORD', 'your password'),
            'charset'   => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix'    => 'your table prefix',
            'strict'    => true,
            'engine'    => null,
        ],
    ],
    // 连接池
    'pools' => [
        // 别名配置，不可以和 connections中的database重名，否则会被识别为连接池配置
        'default_config'  => [
            // 最大连接数
            'max_connection' => 100,
            // 启动时创建连接数
            'min_connection' => 20,
            // 查询超时时间
            'max_wait_time'  => 2000
        ],
        // 使用别名方式引用配置
        'default' => 'default_config',
        // 直接使用数组进行连接池配置
        'other'       => [
            'max_connection' => 200,
            'min_connection' => 20,
            'max_wait_time'  => 2000
        ],
        // 开启连接池调试
        'debug_sample'      => [
            'max_connection' => 200,
            'min_connection' => 20,
            'max_wait_time'  => 2000,
            // 需要指定连接池调试信息输出格式
            'debug' => [
               'enable'   => true,
               'tpl'      => "%.4f|co[%3d]|pool[%s]:%8s, stats: [%3d/%3d], usage: [%3d/%3d], waiting: %3d",
               // timestamp |  cid   |  database  |  action  |    current    |    capacity    |     used    |   current      |   waiting
               // 时间戳     | 协程id |  连接池名    |  动作   |  当前活跃连接数 |  连接池最大容量 | 已使用连接数 |  当前可用连接数  |  等待连接数
               'tpl_fields' => ['timestamp', 'cid',  'database',  'action', 'current', 'capacity', 'used',  'current', 'waiting'],
           ],
           // 或者 直接开启或关闭调试, 调试信息采用默认格式
           'debug' => true
        ],
    ]
];
```

如果需要使用 swoole 异步客户端，需要绑定命名空间下的事件监听器

初始化连接

```
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Log\Helper\CLog;
use Swoft\Server\SwooleEvent;
use SwoftLaravel\Database\DatabaseServiceProvider;

/**
 * Class WorkerStartListener
 *
 * @since 2.0
 *
 * @Listener(event=SwooleEvent::WORKER_START)
 */
class WorkerStartListener implements EventHandlerInterface
{
    /**
     * @param EventInterface $event
     */
    public function handle(EventInterface $event): void
    {
        $confPath = __DIR__ . '/../../config/database.php';
        DatabaseServiceProvider::init($confPath);
        CLog::debug($confPath);
    }
}
```

连接生命周期结束则自动回收

忽略异常注释

```
namespace App;

use Doctrine\Common\Annotations\AnnotationReader;
use Swoft\Annotation\AnnotationRegister;
use Swoft\SwoftApplication;
use function date_default_timezone_set;

/**
* Class Application
*
* @since 2.0
*/
class Application extends SwoftApplication
{
   protected function beforeInit(): void
   {
       parent::beforeInit();

       //忽略异常注释
       AnnotationReader::addGlobalIgnoredName('mixin');

       date_default_timezone_set('Asia/Shanghai');
   }

}
```

使用
--

[](#使用)

```
use SwoftLaravel\Database\Capsule as DB;
use Swoole\Coroutine\Channel;
class Controller {
    public function demo(){
        $user = DB::table('user')
            ->where('name', 'ricky')
            >where('mobile', 13800138000)
            ->get();
    }
    // 需要swoole 4.0.3 以上版本
    // 使用协程并发读数据库
    public function go(){
        $chan =  new Channel(2);
        go(function () use($chan) {
            $code = true;
            $user = DB::connection('ucenter')->table('user')->where('id', 1)->get();
            if ($user == null){
                $code = false;
            }
            $chan->push([$code, 'user', $user]);
        });
        go(function () use($chan){
            $code = true;
            $profile =  DB::connection('ucenter')->table('profile')->where('uid', 1)->get();
            if ($profile == null){
                $code = false;
            }
            $chan->push([$code, 'profile', $profile]);
        });
        $count = 2;
        $success = true;
        $result = [];
        while ($count-- > 0){
            [$code, $field, $result] = $chan->pop();
            $success &= $code;
            $result[$field] = $result;
        }

    }
}

//----------------------------------------------
use Illuminate\Database\Eloquent\Model;
class User extends Model {
    protected $table = 'user';
}
class Controller {
    public function demo(){
        $user = User::find(6);
    }
}
```

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 52.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~22 days

Total

4

Last Release

2464d ago

Major Versions

v1.1.1 → v2.02019-08-15

### Community

Maintainers

![](https://www.gravatar.com/avatar/268cd1b6bad32fb5b798252551524cc34e9c1c75b0a4a1ac85aceb3faaddf7ae?d=identicon)[x1024](/maintainers/x1024)

---

Top Contributors

[![RiceWong](https://avatars.githubusercontent.com/u/31686035?v=4)](https://github.com/RiceWong "RiceWong (9 commits)")[![872409](https://avatars.githubusercontent.com/u/514329?v=4)](https://github.com/872409 "872409 (8 commits)")

### Embed Badge

![Health badge](/badges/swoft-laravel-x1024-database2/health.svg)

```
[![Health](https://phpackages.com/badges/swoft-laravel-x1024-database2/health.svg)](https://phpackages.com/packages/swoft-laravel-x1024-database2)
```

###  Alternatives

[cviebrock/eloquent-sluggable

Easy creation of slugs for your Eloquent models in Laravel

4.0k13.6M253](/packages/cviebrock-eloquent-sluggable)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k33.0M95](/packages/owen-it-laravel-auditing)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)[dragon-code/laravel-data-dumper

Adding data from certain tables when executing the `php artisan schema:dump` console command

3418.6k](/packages/dragon-code-laravel-data-dumper)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
