BeforeSave and AfterSave in Lithium

CakePHP allowed for beforeSave and afterSave callbacks in models. Lithium takes callbacks to the next level with filterable methods. Filters can be added to many of the core object’s methods and to any custom methods if built the right way. Here’s how the lithium version of beforeSave and afterSave works…

// in app/models/MyModel.php
public static function __init(array $options = array()) {
	parent::__init($options);

	static::applyFilter('save', function($self, $params, $chain) {

		// Custom code to be applied before saving the model
                // .....
                // .....

		return $chain->next($self, $params, $chain);
	});

	static::applyFilter('save', function($self, $params, $chain) {
		$data = $chain->next($self, $params, $chain); // process the rest of the filter chain

		// Custom code to be applied after saving the model
                // .....
                // .....			

		return $data;
	});
}

You can even combine the two in the same filter:

// in  your app/models/MyModel.php __init method
	static::applyFilter('save', function($self, $params, $chain) {

		// Custom code to be applied before saving the model

		$data =  $chain->next($self, $params, $chain);

		// Custom code to be applied after saving the model

		return $data;
	});

3 Comments

3 Comments

  1. The best thing about the filter setup is, you don’t actually need two. This is especially helpful when you have some piece of information generated in the before step that you need to use to modify data in the after step. The way you’d usually end up doing this is with some model property, which is prone to breaking on edge cases.

  2. That’s true. The nice thing about Lithium is that we can have this conversation. We’re not forced into a strict organizational pattern. For many cases, one filter probably works fine. However, I can see wanting separate filters for more complex cases. Say you create a filterable authenticate function in your User model. You might want to log the event, set a session message to display after redirecting, check how long it’s been since the user updated his or her profile and change the redirect to the profile edit page, and who knows what else. I’m sure you were probably referring specifically to the save event, but I think the filters will really shine when people start creating complex models. I’m going to amend this post to include a “beforeAndAfterSave” filter. Thanks for the comment!

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>