phalcon: plugin 结合Manager事件管理、dispatcher调度控制器 监听sql日志记录或其他拦截出来

可能用到的类 

phalconmvcuseplugin

PhalconMvcDispatcher as MvcDispatcher

PhalconEventsManager as EventsManager

代码部分

public/index.php:

$di['db'] = function() use($di){
        //log

       //事件管理
       $eventManager = new PhalconEventsManager();

        //继承了plugins的数据库sql操作类
        $eventQSql = new Mydatabase();

        //附上一个侦听者
        $eventManager->attach("db", $eventQSql);

        $db=new DbAdapter(array(
            "host"     => "localhost",
            "username" => "root",
            "password" => "",
            "dbname"   => "demo",
            "charset"  => "utf8"
        ));

        //绑定事件
        $db->setEventsManager($eventManager);
        return $db;
        
};

  

app/plugins/Mydatabase.php

use PhalconDbProfiler,
    PhalconLogger,
    PhalconLoggerAdapterFile as LoggerFile;

class Mydatabase extends PhalconMvcUserPlugin {

    protected $_logger;
    protected $_profiler;

    public function __construct()
    {
        $this->_profiler = $this->profiler;// new  PhalconDbProfiler();
        $this->_logger = new LoggerFile("../log/sql.log");
    }

    public function beforeQuery()
    {
        $this->_logger->log($this->db->getSQLStatement   (), Logger::INFO);
        $this->_profiler->startProfile($this->db->getSQLStatement());
    }

    public function afterQuery()
    {
       $this->_logger->log($this->db->getSQLVariables  (), Logger::INFO);
        $this->_profiler->stopProfile();
    }




}

  每次执行sql语句的时候,发送的sql都会被记录到log文件里面。

原文地址:https://www.cnblogs.com/achengmu/p/6003393.html