Cakephp 的回调函数

Model的Callbacks

我们在model中增加了一些回调函数以帮助你在model操作前后能够织入一些业务逻辑(原文为sneak in,借用了AOP中的织入一词,因为从操作来看这些回调函数等同于AOP中的advice)。为了获得这样的能力,需要使用model中的一些参数并且在你的model中覆写这些方法。

beforeFind(string $conditions)

beforeFind()回调函数是在model的find方法执行前的前置操作。你可以加入任何检索前的业务逻辑。你覆写该方法只要保证在前置操作成功后返回true来执行真正的find方法,返回false中断find方法就可以了。(译注:在一些复杂场景中,需多次持久化的情况下请慎用)。

afterFind(array $results)

使用afterFind回调函数能够更改find方法的返回结果集,或者在检索动作完成后加上一些业务逻辑。该函数的参数$results为经过回调函数处理以后的find检索结果集。

beforeValidate()
beforeValidate回调函数能够在model校验数据之前更改model中的一些数据。同样也可以用来在model校验之前加入更为复杂的额外校验规则。和beforeFind一样,必须保证返回true来调用真正的操作,返回false来中断校验乃至save操作。

beforeSave()

和先前介绍的回调函数类似,在校验完成之后,保存动作之前加入额外的处理(如果校验失败是不会触发该回调函数的)。返回true或者false,不再赘述。
一个比较常见的beforeSave的应用场景就是在保存动作之前格式化日期属性以适应不同的数据库:

// Date/time fields created by HTML Helper:
// This code would be seen in a view
 
$html->dayOptionTag('Event/start');
$html->monthOptionTag('Event/start');
$html->yearOptionTag('Event/start');
$html->hourOptionTag('Event/start');
$html->minuteOptionTag('Event/start');
 
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/
 
// Model callback functions used to stitch date
// data together for storage
// This code would be seen in the Event model:
 
function beforeSave()
{
    $this->data['Event']['start'] = $this->_getDate('Event', 'start');
 
    return true;
}
 
function _getDate($model, $field)
{
    return date('Y-m-d H:i:s', mktime(
        intval($this->data[$model][$field . '_hour']),
        intval($this->data[$model][$field . '_min']),
        null,
        intval($this->data[$model][$field . '_month']),
        intval($this->data[$model][$field . '_day']),
        intval($this->data[$model][$field . '_year'])));
}

afterSave()

放置任何你想要在保存后执行的代码在这个回调函数中。[ToDo 如果保存出错是否会触发?]

beforeDelete()

放置删除前的逻辑代码。想要删除操作执行则返回true,否则返回false。

afterDelete()

放置任何你想要在删除后执行的代码在这个回调函数中。

controller中的回调函数

Cake的controller特别提供了许多回调方法,你可以用它们在一些重要的controller方法之前或者之后插入一些逻辑。如果要利用这些功能,请在你的controller中用这里描述的参数和返回值定义这些方法。

beforeFilter

在每个controller action调用前执行。它是一个检查当前sessoin状态和检查用户角色的好地方。

afterFilter

在每个controller action调用后执行。

beforeRender

在controller逻辑之后,并且在输出视图之前被调用。

Tags: cakephp, php

相关日志

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

还没有评论。

发表评论

(必填)

(必填)


*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Comment moderation is enabled. Your comment may take some time to appear.