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);
}
}
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:
- Retrieve data from service in form of DTO or domain model
- Automap from DTO or domain model to your view model (this can be done in controllers’ actions)
- Return view with a view model
2
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).