CakePHP behaviors are a great way to not only extend model functionality, but also share that functionality across different models, and applications. Using behaviors, we can keep our model code concise and to the point, extracting code that may not be directly related to our business logic, but still affect how our models behave.
In this recipe we will learn how to use model callbacks to automatically retrieve each profile's latest tweets, and how to add a custom validation method to the behavior.
We need some sample models to work with. Follow the Getting ready section of the recipe Adding multiple validation rules.
We will also need a method to list all profiles. Edit your app/controllers/profiles_controller.php
file and add the following index()
method to the ProfilesController
class:
public function index() { $profiles = $this->Profile->find('all'); $this->set(compact('profiles')); }
Create the respective view in a file named app/views...