I'm sure you've been there before. Cleaning up data in every conceivable way that the user could muddle it up just so you can get the information saved or updated. Trimming whitespace, stripping HTML, parsing formatting languages, etc. The problem is that, while necessary, this sucks.
The idea is a simple one: do some stuff with the data just before we pass it off for validation. In the past people have done this in the controller action, perhaps in beforeValidate, hell you may even have some Javascript doing it for you client-side. Now, we've got a one-stop place for all the tweaking.
Anywho, enough chit-chat. Let's begin by showing off some of the fun tidbits it can do.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php class Post extends AppModel { public $behaviors = array('Filterable'); public $filters = array( 'title' => array( 'trim', 'ucwords' ), 'body' => array( 'htmlentities' ) ); }
Here we're using a handful of PHP's functions to cleanup some of our fields. Nothing too special here, but wait, there's more!
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
<?php class Post extends AppModel { public $behaviors = array('Filterable'); public $filters = array( 'title' => array( '_spaceToAsterisks' ), 'body' => array( '_rickRolled' ) ); /** * Takes a string and makes it fabulous. * * @param string $string * @return mixed * @access protected */ protected function _spaceToAsterisks($string) { return str_replace(' ', '*', $string); } /** * Automated Rick Rolling. The best kind there is. * * @param string $string * @return mixed * @access protected */ protected function _rickRolled($string) { return str_replace( 'Rick', 'Rick', $string ); } }
Yup, that's right. Using our own methods to screw tidy things up. But we're not done yet, we've got one more trick up our sleeve...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php class Post extends AppModel { public $behaviors = array('Filterable'); public $filters = array( 'title' => array( array( 'SomeCustomObject', 'staticMethod' ), array( 'SomeCustomObject', 'anotherStaticMethod' ), ) ); }
And we're done. Hopefully the examples make the usage fairly straightforward. If you want you can still perform your own cleanup wherever you'd like, this won't interfere at all.
It's worth noting that none of this is to be a replacement to proper validation, think of it more as an attempt to get your data ready prior to validation. Without further delay, the code.
