独立使用Illuminate\Database,并添加SQL日志功能

0x00 前言

  • slim框架:是一个微型框架,官方文档地址
  • IlluminateDatabase:是一个非常非常优秀的ORM类库(虽然我只用查询构造器),GitHub
  • composer: 是PHP的一个依赖管理工具。

0x01 独立使用IlluminateDatabase

1. 使用composer 安装

使用 composer 安装,直接在项目根目录的命令行里,执行

composer require "Illuminate\Database"

或者在根目录的 composer.jsonrequire 中添加 IlluminateDatabase
如何要监听 SQL ,还需要添加 illuminate/Events

...
"require": {
    ...
    "illuminate/database": "5.5.*",
    "illuminate/Events": "5.5.*",
    ...
  },
...


当前我使用的版本是 v5.5 的,
然后执行 composer update ,来完成其安装。

2. 在框架中shiyong

我在slim中的使用,并没有把它加入slim的容器中,而是使用官方推荐的方式。

$capsule = new Illuminate\Database\Capsule\Manager;
// 创建链接
$capsule->addConnection($container->get('settings')['database']);

$capsule->setEventDispatcher(new Dispatcher(new IlluminateContainer));

// 设置全局静态可访问DB
$capsule->setAsGlobal();

// 启动Eloquent (如果只使用查询构造器,这个可以注释)
$capsule->bootEloquent();  

上面的$container->get('settings')['database']是一个数组,里面是数据库连接参数

  [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'root',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ]

这样使用IlluminateDatabase,我们就没必要每次都要从容器中获取database的链接了。
可以直接类似下面的使用

use Illuminate\Database\Capsule\Manager as DB;

$obj_list = DB::table('group_member as m')
    ->select($select)
    ->leftJoin($this->table . ' as g', 'g.id', '=', 'm.group_id')
    ->where($where)
    ->get();

而不是每次都要

$c->get('database')->connection()->table('XXX')->get(['XXX','XXX']);

虽然整体没有降低耦合度,但是一般项目中,没有频繁更改database类库的可能性吧,,而且从代码层上看,更干净,更整洁(可能这只是我个人的观点0.0)。

0x02 添加SQL日志

所谓的SQL日志,就是所有的sql执行的记录。
形如:

2018-06-23 10:59:36 select `g`.`name` as `groupname`, `g`.`id`, `g`.`image` as `avatar` from `group_member` as `m` left join `group` as `g` on `g`.`id` = `m`.`group_id` where (`g`.`is_deleted` = '0' and `m`.`is_deleted` = '0' and `m`.`uid` = '1')  [36.18 ms]

这种,包含执行的时间,具体的SQL,还有执行所需时间。这对于开发的时候排查定位bug,有很大的帮助。也是因为昨天公司项目(lumen框架)中利用SQL日志准确的分析出bug,然后就迫不及待的为自己做的小玩意添加这个功能。

其实,IlluminateDatabase 已经做了这个功能,配置,开启添加具体的SQL记录操作。

在加载项目启动的路径中添加即可,亦可以放在全局的路由的中间件中。

DB::connection('default')->listen(function ($query) use ($logger) {
    $sql = date('Y-m-d H:i:s',time())."\n" . vsprintf(str_replace("?", "'%s'", $query->sql), $query->bindings) . " \n[" . $query->time . ' ms] ';
    // 把SQL写入到日志文件中
    $logger->debug($sql);
});

至此,就完成了 IlluminateDatabase 的安装、使用以及SQL日志的添加。

SQLilluminate/Database

我来吐槽

*

*

已有 3 条评论

  1. MichaelTib

    NordVPN vs ExpressVPN: nordvpn onion over vpn
    Go like greased lightning, security and payment compared who makes nordvpn When you're about to perpetrate to a monthly or annually practical special network subscription, there are three factors to weigh: briskness, care, and price. nordvpn free NordVPN and ExpressVPN are We leading VPN competitors, in no minuscule part because of their exceptional act when we stress-tested their isolation and refuge promises. nordvpn port forwarding
    Both NordVPN and ExpressVPN are based in countries with competitively stringent privacy laws principally considered outside nordvpn subscription
    the reach of US and brightness allies take direction at tech companies over encryption, how much nordvpn cost and both come with a obliterate switch, which prevents data communication in victim your service cuts out. nordvpn youtube Both are chock-a-block in support of media torrenting and accessing Netflix when you're traveling out of the country. Both furnish 24/7 live-chat and email client servicing support. nordvpn how to cancel subscription nordvpn on ps4 how much does nordvpn cost per month
    why nordvpn is best
    nordvpn with openvpn
    nordvpn account free
    nordvpn install
    nordvpn keychain access

  2. order cialis online

    I get pleasure from, lead to I found exactly what I
    was taking a look for. You have ended my four day long hunt!
    God Bless you man. Have a great day. Bye

    1. 不息

      Thank you! Have a nice day.