tags:

views:

65

answers:

2

is it usual to use controllers in models?

then you have to include the controller in the model?

+2  A: 

No it is not common. You should never have to use your controllers from your model.

If you feel the need to, it probably means code that is currently in your controller should live in a shared library, or actually be in the model to begin with.

It is of course proper to use a model from a controller.

Update

Code that doesn't directly relate to a specific database table/record (model), or doesn't directly respond to a user's action (controller), would be a good candidate for a utilities or library file.

This is more normal, and where you load it depends on if you are using a framework or not. If it just your custom app, you can just do a require_once in your model and use the utility methods from there.

Doug Neiner
but what if i want to log things within a model (errors and so on) and i got a utilities class as a controller with a log method?
weng
am i mixing up a controller with a class? could you call classes (utilities, validations) from a model?
weng
Controllers are classes, you can have a controller class for handling exceptions and logging.
Anthony Forloney
but i think controllers are the redirectors (models -> views) and not handling logging and exceptions. that will be other classes which arent controllers. am i right guys? so in models you can use classes for eg. validations and logging?
weng
@noname that is correct, utility functions and logging would not be a controller.
Doug Neiner
$doug: so i can use helper classes in models?
weng
Yes. It makes sense to have shared helpers available outside of a single model (and of course included in them as needed).
Doug Neiner
+2  A: 

Models should not be using controllers.

To clarify, using the MVC pattern, the user communicates with the controller which manipulates the model which dispatches its results to the view back to the user.

alt text

Image taken from The Model-View-Controller (MVC) Design Pattern for PHP

Update to Doug's response:

The most logical way to explain how the components work is by starting from the model, then going through the controller, and finally reaching the view. And "MCV" would not have been nearly as appealing a name to the ear as "MVC."

Taken from Chapter 1 of Beginning ASP.NET MVC 1.0 by Simone Chiaretta and Keyvan Nayyeri.

Anthony Forloney
so then its a CMV pattern, :) I never understand why M comes first.
Doug Neiner
I read somewhere reason being is that its something along the lines of that it is easier phonetically to pronounce *MVC* than *CMV*. If I can find the actual reference, I'll try to remember it.
Anthony Forloney
couldnt it be user to controller to model and back to controller which insert the data from the model to an appropiate view?
weng
Technically yes, something along those lines can be done.
Anthony Forloney