Lithium Model Filter

I am currently developing a Lithium application that requires various objects to be added to the object before calling the save () function.

Ideally, I could write a filter to apply to the Model class (the base model that other models extend to), for example:

Model::applyFilter('save', function($self, $params, $chain) {
    // Logic here
});

      

Is it possible? If so, is it a boot file?

+3


source to share


2 answers


If I don't understand what you are talking about, you want, for example, to automatically add the value for 'created' or 'modified' to the object before saving.

This is how I do it.

From my extensions/data/Model.php



<?php
namespace app\extensions\data;
use lithium\security\Password;

class Model extends \lithium\data\Model {

    public static function __init() {
        parent::__init();

        // {{{ Filters
        static::applyFilter('save', function($self, $params, $chain) {
            $date   = date('Y-m-d H:i:s', time());
            $schema = $self::schema();

            //do these things only if they don't exist (i.e.  on creation of object)
            if (!$params['entity']->exists()) {

                //hash password
                if (isset($params['data']['password'])) {
                    $params['data']['password'] = Password::hash($params['data']['password']);
                }

                //if 'created' doesn't already exist and is defined in the schema...
                if (empty($params['date']['created']) && array_key_exists('created', $schema)) {
                    $params['data']['created'] = $date;
                }
            }

            if (array_key_exists('modified', $schema)) {
                $params['data']['modified'] = $date;
            }
            return $chain->next($self, $params, $chain);
        });
        // }}}
    }
}

?>

      

I also have password hashing. You can remove this without affecting any functionality.

+5


source


Filters do not support inheritance *.

Better to use OOP and have a class BaseModel

with an overridden save () method and from which all your application models inherit.

Another way is to lazily apply filters to each model in the load file. For example:



Filters::apply('app\models\Documents', 'save', $timestamp);
Filters::apply('app\models\Queries', 'save', $timestamp);
Filters::apply('app\models\Projects', 'save', $timestamp);

      

with $timestamp

closure

* Filters are scheduled to inherit but not yet completed

+4


source







All Articles