views:

31

answers:

2

Any idea on how best to add a message to flash messenger from the model?

As FlashMessenger is an action helper, this seems not to be possible, so the obvious solution is to create an internal message object in the model, and return that to the controller from where you can use addMessage(). But if you want to return something else as well, this falls down.

Another idea is an additional session namespace for these internal messages, which is then merged in with the Flash Messenger namespace messages at output time?

Anyone have any thoughts or experience on this? Cheers.

A: 

Both routes sound valid.

One idea would be to add a $message arrayto your model, which the action helper can access to retrieve the messages. This way you could return multiple messages at once.

Another option would be to use a Subject/Observer pattern. Have your models implement the Subject interface and when you need to output messages, notify the observers, e.g. the flash messenger (for which you would have to implement the Observer interface).

Gordon
Thanks Gordon - interesting ideas, but thinking about it further it may be that a number of models/resources may be used (and may therefore generate messages) as a result of a given controller action, and therefore I will have to test all models for messages, which will end up messy to say the least. If only there was a way to call an action helper within a model!
Dan
@Dan the Subject/Observer Pattern will easily manage messages from multiple models. You just notify your custom FlashMessenger from whichever model you like - without putting the messenger in the model. That's important because the messenger should not be inside the Model. It belongs to the presentation layer.
Gordon
Thanks Gordon, have used Goran's static call below
Dan
@Dan Ah well, Goran's solution is exactly what you shouldn't do. With that approach, you couple the presentation layer to the model. The model should be kept independent from the presentation layer (the V and C of MVC). Using the static call also hardcodes the dependency on the HelperBroker into all using model classes. If you want to use the Flash Messenger at any cost in your model, then at least inject the messenger into the model from the controller. Sorry, but I think this approach is poor design.
Gordon
A: 

You can fetch the FlashMessenger from your model like this:

$messenger = Zend_Controller_Action_HelperBroker::getStaticHelper('flashMessenger');
$messenger->addMessage('test message');
Goran Jurić
Thanks Goran, that's sorted me out a treat!
Dan