CakePHP - Access session data in Model::afterSave()
I have MyModel
that, whenever it is created or updated, I want to insert a row into my_model_changes (MyModelChange)
that is a log of all changes.
The problem is that I need MyModelChange
to be able to save the current user's ID, so that it stores who authorised the change to MyModel
.
I know the model shouldn't be able to access the Auth session in MVC. However, every change to MyModel
must be logged, and so I don't want to leave it up to people to remember to do this in a controller every time they modify the model, because there is a risk it will be forgotten or not done properly, in which case the log won't be complete. Instead, I want to use MyModel::afterSave()
so that it is开发者_如何学C automated and will always happen properly.
So how do I get MyModel
to find the Auth user's ID?
Maybe my solution is not the most elegant way but I used it in my app and it worked. Before saving in the controller I extend $this->data with the user_id like this:
$this->data['MyModel']['user_id']=$this->Auth->user('id');
so I can use it in my model afterSave method. I hope it could help.
Is it not possible to do what you're wanting to do in the app_controller.php's beforeFilter? That way you don't have to set anything in the other controllers, except the parent::beforeFilter() ofcourse if you override it.
But if it's really needed, you can put this in your Model to access session data:
App::import('Component', 'SessionComponent');
$Session = new SessionComponent();
精彩评论