1

Where should the Models be instatiated in a MVC arhitecture? I understand the preferred way would be outside controllers, in a bootstrap file and injected using a Dependecy Injection Container. But most of the models I'm working with depend on run time parameters.

//PHP Example
class UserController {
   protected $objUser;
   protected $objDictionary;

   public function Show() {
       $objUserMapper = new UserMapper();
       $this->objUser = $objUserMapper->FindById($_GET['id']);
       $this->objDictionary = new Dictionary($this->objUser->Language);
   }
}

2 Answers 2

1

View models are generally instantiated in controllers.

Domain models shouldn't be used in controllers unless project is really small.

Inversion of control containers are normally used to inject services that talk to the business layer. This becomes useful when you write your application using TDD as you would normally mock calls to your services.

General flow is:

  1. Retrieve data from service in form of DTO or domain model
  2. Automap from DTO or domain model to your view model (this can be done in controllers' actions)
  3. Return view with a view model
2
  • 1
    I added a php example using the data mapper pattern. In this case is it ok to create the UserMapper inside the UserController? Also what do you think about the Dictionary instantation?
    – johnlemon
    Sep 16, 2013 at 16:40
  • I'm not a PHP developer but it's fine to map from domain model or DTO to a view model. If you don't do it in a controller, where else are you going to do it? You don't want to have mapping logic in the view model as it doesn't belong there.
    – CodeART
    Sep 17, 2013 at 7:23
0

In the MVC pattern, the Controller instantiates both Models and Views.

It can do so directly or via other means, typically some form of factory or a IoC container. In any case the "new instance" of the Model is held by the controller which passes it to the View.

Also, the view may have its own underlying class (this depends on which MVC framework you are using) and may not receive the model directly - it's OK if the controller translates the "Model language" (business concerns) to the "View language" (presentation concerns).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.