本质上,这归结为是否可以在 CakePHP 中使用模型回调来挂入和注销。
我尝试执行的操作的目的是在每次用户登录或注销应用程序时记录。
我设置了一个自定义日志流,以将适当的值保存到数据库中。
在我的用户控制器中.php我有这个:
public function login() {
// Check if we have post data
if( $this->request->is('post') ) {
// Reset any user data hanging around
$this->User->create();
// Log our user in
if( $this->Auth->login() ) {
// Success, redirect with a message
$this->Session->setFlash( 'You have successfully logged in' );
$this->redirect( $this->Auth->loginRedirect );
} else {
// Failure, flash a message
$this->Session->setFlash( 'Incorrect Username/Password' );
}
}
}
从我所看到的相当标准。
然后,我在模型中寻找一些东西来挂钩到登录和注销操作中,以使用它写入数据库。
CakeLog::write( 'Notice', "$username has logged in." );
我知道我可以以另一种方式执行此操作,但是我被特别要求通过模型回调执行此操作。
关于$this->Auth->loginRedirect
有一个方法:
$this->Auth->redirectUrl()
如示例中记录和显示的:http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
但除此之外,您可以简单地创建模型方法并从登录中调用它们:
if ($this->Auth->login()) {
$this->User->loggedInCallback($username);
}
您可以根据需要将尽可能多的逻辑和登录放入该方法中。
没有必要让它变得更加困难。