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

可能用到的类 

phalcon\mvc\use\plugin

Phalcon\Mvc\Dispatcher as MvcDispatcher

Phalcon\Events\Manager as EventsManager

 

代码部分

public/index.php:

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

       //事件管理
       $eventManager = new \Phalcon\Events\Manager();

        //继承了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 Phalcon\Db\Profiler,
    Phalcon\Logger,
    Phalcon\Logger\Adapter\File as LoggerFile;

class Mydatabase extends \Phalcon\Mvc\User\Plugin {

    protected $_logger;
    protected $_profiler;

    public function __construct()
    {
        $this->_profiler = $this->profiler;// new  \Phalcon\Db\Profiler();
        $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文件里面。

 

posted @ 2016-10-27 11:44  穆晟铭  阅读(1144)  评论(0编辑  收藏  举报