Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/**
 * TouchBehavior
 *
 * Usage in model:
 *
 * 1) make sure model's $actsAs array contains something like (those keys are
 * default values You don't need to specify)
 *
 * 'Touch' => array('field' => 'last_access', 'timestamp'=>'Y-m-d H:i:s')
 *
 * 2) You can call $this->ModelName->touch() or $this->ModelName->touch(3) in
 * controller
 *
 * 3) this behavior implements beforeSave() callback for updating value of last
 * access field ;)
 */
class TouchBehavior extends ModelBehavior {
    /**
     * Default model settings
     */
    var $defaultSettings = array('field' => 'last_access', 'timestamp' => 'Y-m-d H:i:s');
 
    /**
     * Prepare model settings
     *
     * Redefines parent method
     */
    function setup(&$model, $config = array()) {
       $field = $this->defaultSettings['field'];
 
        if (!empty($config['field'])) {
           $field = $config['field'];
       }
 
        // conditional initialization of settings for this model
        if ($model->hasField($field)) {
           $timestamp = $this->defaultSettings['timestamp'];
           
            if (!empty($config['timestamp'])) {
               $timestamp = $config['timestamp'];
           }
 
            $this->settings[$model->name] = array(
               'field' => $field,
               'timestamp' => $timestamp
           );
       }
    }
 
    /**
     * Updates only field for last access information
     */
    function touch(&$model, $args = array()) {
       if (isset($this->settings[$model->name])) {
           if (!empty($args[0])) {
               $model->id = $args[0];
           }
 
            if (!empty($model->id)) {
               $field = $this->settings[$model->name]['field'];
 
                // uses $fieldList argument, so data can be prepared in beforeSave()
                return $model->save(null, false, array($field));
           }
        }
    }
 
    /**
     * Modify last access field on every save
     *
     * Redefines parent method
     */
    function beforeSave(&$model) {
       if (isset($this->settings[$model->name])) {
           $field = $this->settings[$model->name]['field'];
           $timestamp = $this->settings[$model->name]['timestamp'];
 
            $model->data[$model->name][$field] = date($timestamp);
       }
    }
}
?>