I need get the MySql query executed before Save, Update, Delete for create a personal LOG (audit).
I use $model->save() and $model->delete() standard from CActiveRecord.
Any know how i can do this?
Thanks to all!
You can use the methods
class Objects extends CActiveRecord
{
protected function beforeSave()
{
// Your code goes here
}
protected function beforeDelete()
{
// Your code goes here
}
}
For Logging of query you refer this thread Logging
u can also see the log on the page by just uncommenting the follwing code in config.main file
// uncomment the following to show log messages on web pages
array(
'class'=>'CWebLogRoute',
),
Related
Trying to learn events in Yii 2. I found a few resources. The link I got more attention is here.
How to use events in yii2?
In the first comment itself he explains with an example. Say for an instance we have 10 things to do after registration - events comes handy in that situation.
Calling that function is a big deal? The same thing is happening inside the model init method:
$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
$this->on(self::EVENT_NEW_USER, [$this, 'notification']);
My question is what is the point of using events? How should I get full benefit of using them. Please note this question is purely a part of learning Yii 2. Please explain with an example. Thanks in advance.
I use triggering events for written (by default) events like before validation or before deletion. Here's an example why such things are good.
Imagine that you have some users. And some users (administrators, for example) can edit other users. But you want to make sure that specific rules are being followed (let's take this: Only main administrator can create new users and main administrator cannot be deleted). Then what you can do is use these written default events.
In User model (assuming User models holds all users) you can write init() and all additional methods you have defined in init():
public function init()
{
$this->on(self::EVENT_BEFORE_DELETE, [$this, 'deletionProcess']);
$this->on(self::EVENT_BEFORE_INSERT, [$this, 'insertionProcess']);
parent::init();
}
public function deletionProcess()
{
// Operations that are handled before deleting user, for example:
if ($this->id == 1) {
throw new HttpException('You cannot delete main administrator!');
}
}
public function insertionProcess()
{
// Operations that are handled before inserting new row, for example:
if (Yii::$app->user->identity->id != 1) {
throw new HttpException('Only the main administrator can create new users!');
}
}
Constants like self::EVENT_BEFORE_DELETE are already defined and, as the name suggests, this one is triggered before deleting a row.
Now in any controller we can write an example that triggers both events:
public function actionIndex()
{
$model = new User();
$model->scenario = User::SCENARIO_INSERT;
$model->name = "Paul";
$model->save(); // `EVENT_BEFORE_INSERT` will be triggered
$model2 = User::findOne(2);
$model2->delete(); // `EVENT_BEFORE_DELETE` will be trigerred
// Something else
}
friends i am using yii log to genrate log file for each user on the base of its id for its actions but when i am trying to set log file path dynamically then its not working please help me to find the way that how i can set dynamically log file path for logged in user.
$logger = new CFileLogRoute();
$logger->setLogPath("/app/protected/runtime/user-log/");
$logger->setLogFile("kumar-121.log");
$message='langusge changed from ';
Yii::log($message, 'CsvError', 'system.*');
buts it not working at all. please help me in this
Thanks friends but i got the answer what is did i firstly created my custom class and extand CFileLogRoute
then i just overwrite some parent file functions
class MyFileLogRoute extends CFileLogRoute{
public function formatLogMessage($message,$level,$category,$time)
{
return #date('Y/m/d H:i:s',$time)." - $message\n";
}
public function getLogFile()
{
return 'user-'.(int)Yii::app()->user->id.'.log';
}
public function setLogFile($value)
{
parent::setLogFile($value . (int)Yii::app()->user->id);
}
and this works perfect for me.
my first method i have created to remove level category from log file so it just simple log file
anyhow thanks
I have build a notification widget in Yii framework which is called every page and gives the user notifications. Now I would like to update those notifications automatically every 10 seconds with Ajax. The structure is as follows:
<?php
class NotificationsWidget extends CWidget {
public function init(){
}
public function run() {
}
What is the best way to do this? I have searched everywhere, but I cannot seem to find the answer. Maybe I'm just looking with the wrong keywords.. If anyone has another (better) way to do this, please! Only restriction is that it has to be loaded into the interface layout and update at least every 10 seconds.
Thanks a lot:)
You setup an action in your controller and poll it every 10 seconds, if there is update it will return the notification from a partial view, if there is no update nothing is returned, this is a skeleton implementation to give you an idea, note it will not work as is.
In your layout file
...
// Your normal layout content
<?php Yii::app()->clientScript->registerScript("poll_ajax_notifications",
'function getNotification(){'.
CHtml::ajax(array(
'url'=>array("//notifications/update"),
'dataType'=>'html',
'type'=>'GET',
'update'=>'#divcontainingNotificationWidget',
)
) . '. }
timer = setTimeout("getNotification()", 10000);
', CClientScript::POS_END);
In your Notifications controller
class NotificationsController extends CController {
....
public function actionUpdate(){
$user = Yii::app()->user->id;
// Your logic logic for finding notifications
if($notificationPresent){ // or any validation to check whether to push data or not
$this->renderPartial('_notificationWidget',array('widgetData'=>$widgetData)); // pass data required by widget here
}
Yii::app()->end();
}
...
}
Finally create a partial view in views/notifications folder called _notificationsWidget.php
In your view place your widget call
<?php
$this->widget('path.to.my.widget',array(
//widget parameters
));
I want to cache a query in CodeIgniter. What I did for my test is make a controller, that I named show.php:
class Show extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('rejaal_show');
}
public function _remap($method = '',$param = array())
{
$method = intval($method);
$this->output->cache(5);
var_dump ($this->rejaal_show->temp($method));
}
}
And a model that I named rejaal_show.php:
public function temp($id)
{
$this->db->cache_on();
$this->db->where('id',$id);
$query = $this->db->get('system_store_table');
return $query->result();
}
When I call http://localhost/rejaal/show/1 for the first time, it will show a result, but when I call it for the second time, it does not show anything.
I should delete the query cache file to show it again? How should I solve this problem?
With special thanks for your attention.
Can you confirm that you have set $db['default']['cachedir'] to the path of a writable folder in application/config/database.php and that when the query is first run it creates a cache file in there?
The only other reason I can think of for it failing is by your use of the _remap override. I have not used db caching using _remap, but know that CodeIgniter creates a folder called controller+action in your cache folder, and might not be handled very well if using remap? Someone correct me if I am wrong about this.
In the CodeIgniter User Guide page for Web Page Caching, it says:
Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for your controller with a view.
Do your var_dump inside a view.
Hi
I'm trying to figure the best way to execute a PHP script inside Joomla!
I want to redirect users if they are not from X country (already have a database and the script)
I found this extension but I want to make my own stuff http://bit.ly/daenzU
1) How could I execute the script once for each visitor? Working with Cookies?
2) As I'll put the script inside Joomla! template, I'll modify templates/XXX/index.php
3) Based on 2), Joomla! loads templates/XXX/index.php each time a page loads, so I have to avoid redirection script to be executed twice for an user
Thanks in advance for your ideas and suggestions
Just remember that, in Joomla 3.x, (according to the docs) in order to check an information about the user before the 'Login' event, you need to create you plugin in the 'authentication' context. That is, you need to have your plugin at 'root_to_joomla/plugins/authentication/myplugin/myplugin.php'.
Also, your plugin should be a class named PlgAuthenticationMyplugin, it shold extend the base plugin class 'JPlugin' and should have a public method named 'onUserAuthenticate'.
<?php
...
class PlgAuthenticationMyplugin extends JPlugin {
...
public function onUserAuthenticate($credentials, $options, &$response)
{
//your code here (check the users location or whatever)
}
....
If you want to do that after the Login event, your plugin should be at the user context, at root_to_joomla/plugins/user/myplugin/myplugin.php. And should have a public method 'onUserLogin'.
<?php
class PlgUserMyplugin extends JPLugin {
...
public function onUserLogin($user, $options)
{
//your test goes here
}
...
You can see all other User related events here.
DO NOT modify the template, this will do the trick but is not the right place.
I advise you to create a plug-in, see Joomla docs on plug-ins. Here is event execution order of events.
Create a system plugin and implement onAfterInitialise method. In that method add all of your code.
To prevent the execution of script twice for each user set the user state, see Joomla documentation for states. You can also use session $session = JFactory::getSession(), see documentation.
Here is code... for your plug-in.
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.plugin.plugin' );
class plgMyPlugin extends JPlugin {
//
public function __construct(){
// your code here
}
//
public function onAfterInitialise(){
$app = JFactory::getApplication();
//
$state = $app->getUserStateFromRequest( "plgMyPlugin.is_processed", 'is_processed', null );
if (!$state){
// your code here
// ....
// Set the Steate to prevent from execution
$app->setUserState( "plgMyPlugin.is_processed", 1 );
}
}
}