将项目添加到队列的链接方法


Chaining methods for adding items to a queue

我正在编写一个日志类,它有几种方法,如infoerrorwarning,可以将日志条目插入数据库。

到目前为止,这些方法中的每一个都直接进行了数据库插入。当涉及到批处理时,这不是很好的性能。我现在想通过创建一个队列来解决这个问题,并且在任务结束时只生成并激发一个insert语句。

我现在不确定以下内容是否有意义或是良好的实践。我现在要做的是链接方法来启动和提交一个队列,比如:

Log::queue()->info('Just somehting')->warning('Strange stuff')->submit();

或者如果我不想直接插入:

Log::info('Just something');

例如,类结构如下所示:

class Log {
    protected $queue = array();
    protected $isQueued = false;
    public function queue() {
        $this->isQueued = true;
        return $this;
    }
    public function info() {
        if($this->isQueued) {
            //Add to queue
        } else {
            //Insert in db
        }
        return $this;
    }
    //All the other log types following...
    public function submit() {
        //Generate single insert statement from queue and insert it
    }
}

我使用的是Laravel外观,因此使用了静态调用。

这个设计有什么问题吗?我不确定,因为例如Log::submit()本身完全没有意义,但却是可能的。这有关系吗?

您可能应该删除队列/提交方法,而不是获取传入日志并将其存储在对象上的数组中,然后您可以使用类似App::shutdown(function() {...})的回调来告诉它,一旦应用程序完成了对请求的服务,就将内存中的日志字符串提交到数据库。

同样值得一提的是,如果你不局限于使用SQL数据库,那么已经有几个针对Redis、Mongo等的现有数据库Monolog处理程序。底层Monolog实例可通过Log::getMonolog()获得。