Yii保存对ajax请求的日志访问 [英] Yii save log access to ajax requests

查看:29
本文介绍了Yii保存对ajax请求的日志访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的数据库中保存一个包含用户访问的所有链接的日志访问.问题是我无法保存ajax请求的时间,因为我没有访问链接,例如当我删除一个寄存器时,它是由ajax调用产生的.如何全局检测ajax调用时间并保存在我的数据库中?

I'd like to save a log access in my database with all links that the user visits. The problem is that I can't save when is ajax request because I don't visit the link, for example when I delete a register, it's made by ajax call. How can I globally detect when is the ajax call and save in my database?

我保存普通页面寄存器(我访问的网址)的代码是:

My code to save the normal page registers (url that I visit) is:

$ip = CHttpRequest::getUserHostAddress(); // get ip
$id_user = Yii::app()->user->getId();   //get user
$url = Yii::app()->request->requestUri; //get url       


$sql = "INSERT INTO log(id_user, date, hour, url, ip) VALUES (:id_user, 'now', 'now', :url, :ip)";
$rawData = Yii::app()->db->createCommand($sql)->queryAll(true, array(':id_user'=>$id_user,':url'=>$url,':ip'=>$ip));

推荐答案

正如我在评论和 Rowan 的回答中提到的,这可能是通过扩展您的基本控制器最容易做到的.

As mentioned in my comment and Rowan's answer, this is likely easiest to do by extending your base controller.

在 testdrive 示例应用程序中,您会注意到有一个 protected/components/Controller.php.如果您查看源代码,您会看到它扩展了 CController.

In the testdrive sample app, you'll notice there's a protected/components/Controller.php. If you look at the source, you'll see that that extends CController.

您还会注意到 protected/controllers 中的控制器扩展了 Controller,这意味着它们将包含 Controller 拥有的所有内容,根据定义,控制器拥有 CController 拥有的所有内容.

You'll also notice that the controllers at protected/controllers extend Controller, meaning that they'll include everything that Controller has, which by definition has everything that CController has.

所以,建议遵循这个习惯用法,然后在 protected/components/Controller.php 中,覆盖 beforeAction(),默认情况下除了返回 true 之外什么都不做.因此,在 protected/components/Controller.php 中,只需重新定义 beforeAction() 以包含您的日志记录语句和任何必要的逻辑.

So, the advice is to follows this idiom, and then in protected/components/Controller.php, override beforeAction(), which by default does nothing except return true. So in protected/components/Controller.php, just redefine beforeAction() to include your logging statements and any logic necessary.

哦,针对您的未访问 url"的评论,您确实意识到 AJAX 调用仍在访问某种形式的 URL,对吗?即通过 url 键指定的那个?所以如果你真的想要,你可以将日志添加到你的 AJAX 调用的任何 url,但这会很快变得很麻烦,而且你会违反 DRY 原则.

Oh, and in response to your comment that "no url is visited", you do realize that an AJAX call is still visiting a URL of some form right? Namely the one specified via the url key? So if you really wanted, you could add the logging to whatever url that your AJAX is calling, but this is going to quickly become cumbersome, and you'll be violating the DRY principle.

这篇关于Yii保存对ajax请求的日志访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆