hyperf 数据库模型事件


sql执行日志

控制器 app/Controller/IndexController.php

<?php
namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use App\Model\User;

/**
 * @AutoController();
 */
class IndexController
{
        public function index(){
                $users = User::where('id', 5)->update(['name' => 'xiaoming5']);
                return $users;
        }
}

监听器 app/Listener/DbQueryExecutedListener.php

<?php

declare(strict_types=1);

namespace App\Listener;

use Hyperf\Database\Events\QueryExecuted;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Arr;
use Hyperf\Utils\Str;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * @Listener
 */
class DbQueryExecutedListener implements ListenerInterface
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(ContainerInterface $container)
    {
        $this->logger = $container->get(LoggerFactory::class)->get('sql');
    }

    public function listen(): array
    {
        return [
            QueryExecuted::class,
        ];
    }

    /**
     * @param QueryExecuted $event
     */
    public function process(object $event)
    {
        if ($event instanceof QueryExecuted) {
            $sql = $event->sql;
            if (! Arr::isAssoc($event->bindings)) {
                foreach ($event->bindings as $key => $value) {
                    $sql = Str::replaceFirst('?', "'{$value}'", $sql);
                }
            }

            $this->logger->info(sprintf('[%s] %s', $event->time, $sql));
        }
    }
}

监听器配置 config/autoload/listener.php

<?php

declare(strict_types=1);

return [
        \App\Listener\UserRegisteredListener::class,
        \App\Listener\DbQueryExecutedListener::class,
];

访问测试

curl 118.195.173.53:9501/index/index

日志 runtime/logs/hyperf.log

[2021-09-28 20:32:02] sql.INFO: [13.64] update `user` set `name` = 'xiaoming5' where `id` = '5' [] []
[2021-09-28 20:32:02] sql.INFO: [13.64] update `user` set `name` = 'xiaoming5' where `id` = '5' [] []

模型事件

控制器 app/Controller/IndexController.php

<?php
namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use App\Model\User;

/**
 * @AutoController();
 */
class IndexController
{
        public function index(){
                $user = new User();
                $user->name = 'model_event_test';
                $user->save();
        }
}

user模型 app/Model/User.php

<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Database\Model\Events\Saving;

/**
 * @property $id
 * @property $name
 * @property $age
 * @property $role_id
 * @property $status
 */
class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['id','name','age','role_id','status'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];

    /**
     * 不自动维护时间戳
     * @var bool
     */
    public  $timestamps = false;

    /**
     * 模型事件saving
     * 自动添加age,role_id,status字段值
     */
    public function saving(Saving $event)
    {
           $this->age = 20;
           $this->role_id = 1;
           $this->status = 1;
    }
}

测试

curl 118.195.173.53:9501/index/index

user表记录

mysql> select * from user;
+----+------------------+------+---------+--------+
| id | name             | age  | role_id | status |
+----+------------------+------+---------+--------+
|  1 | xiaohong         |   24 |       1 |      1 |
|  2 | huyongjian2      |   24 |       2 |      0 |
|  4 | xiaoming         |   28 |       2 |      1 |
|  5 | xiaoming5        |   30 |       2 |      1 |
|  6 | huyongjian1      |   30 |       2 |      1 |
|  7 | huyongjian2      |   31 |       2 |      1 |
|  8 | xiaohong         |   24 |       1 |      1 |
| 11 | model_event_test |   20 |       1 |      1 |
+----+------------------+------+---------+--------+
8 rows in set (0.00 sec)

注:id=11的记录 name是IndexController赋值的,age,role_id,status是User模型saving方法赋值的

钩子函数

事件名    触发实际    是否阻断    备注
booting    模型首次加载前    否    进程生命周期中只会触发一次
booted    模型首次加载后    否    进程生命周期中只会触发一次
retrieved    填充数据后    否    每当模型从 DB 或缓存查询出来后触发
creating    数据创建时    是    
created    数据创建后    否    
updating    数据更新时    是    
updated    数据更新后    否    
saving    数据创建或更新时    是    
saved    数据创建或更新后    否    
restoring    软删除数据恢复时    是    
restored    软删除数据恢复后    否    
deleting    数据删除时    是    
deleted    数据删除后    否    
forceDeleted    数据强制删除后    否


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM