4

Folks, first time on CodeReview - just looking for some input in creating some automation in CakePHP, wondering if this is best used a component or a behavior. It's model driven but involves logic and processing. Here's the scoop:

The app I'm creating requires the user to be notified when a model meets certain conditions - additionally data in the affected model or a related model might need to be changed. For example, if a customer model is saved with a certain state/province, assign that customer to a sales rep (by changing a relational field) and notify them through a Growl or an Email. So it's data driven, for sure, suggesting behavior, presumably afterSave()

But it also requires logic and other utilities not typically used in the model or behavior (email, for example and Session/system configuration/user preferences) - functionality typically found in a controller/component and not readily available to a model or behavior.

So is this best developed as a behavior or a component?

Any tips on how to approach by Cake Guru's this would be much appreciated.

Thanks in advance.

1 Answers1

1

Model and behaviour are quite the same thing. A behaviour extends the functionality of a model. The choice between that lies in complexity and re-usability. If you don't know what's best you could post a separate question on that with corresponding code to define what's the best solution.

The app I'm creating requires the user to be notified when a model meets certain conditions

For this kind of notifications you should look at the Events system of CakePHP. That will create the separation you want to have.

In general it means that you check the condition in your model (or behaviour) and throw an Event when the conditions is met. Other code will respond to that event and handle sending out the notification etc.

The Event listener could then also be modified, for example: For performance reasons you might want to put the notification in a queue to offload the work so the response becomes faster.

additionally data in the affected model or a related model might need to be changed. assign that customer to a sales rep (by changing a relational field)

This is more something to do directly in the model or behaviour. I would not implement an Event here directly. You could hook this up for example in beforeValidate. Make sure the salesrep_id is required. Then in your code you check which one you should select and enter the right ID.

That way a client is aways assigned to a sales rep and that is being validated.

If the code for selecting a sales rep is complex or has to be re-used you can separate that out into a behaviour as well.

[edit] more on the events system: http://book.cakephp.org/2.0/en/core-libraries/events.html

Luc Franken
  • 2,664
  • 15
  • 9