So recently I was asked for my thoughts on model view controller MVC and where business logic should be done. While I hope I answered the question well enough, I wanted to expand on my thoughts and maybe see what others thought.

What should a model know?
Often you see models represented as bare bean or container classes filled only with properties and setters and getters. Normally these properties relate to fields in some form of database. So the model only knows about the data it contains. This is a good thing. However it is also a very powerful piece of information. In my opinion the model should have many helper methods on top of the normal setters and getters to formulate the data as cleanly as possible for a nice skinny view and controller and also allowing improved decoupling of the code. The model should never contain any html, but an example of a helper method in a java bean model might be something like:

class Person{
private String firstName;
private String secondName;

/..Setter and Getters../

//helpers
public String getFullName(){
return firstName+" "+secondName;
}
}

Another example of a helper method but with a bit more meat to it:

class Customer implements CustomerModel {
private List<ProductModel> customerProducts;

//normally would be a Hibernate hasMany mapping
public List<ProductModel> getCustomerProducts(){
if(customerProducts == null){
Mapper mapper = new ProductMapper();
customerProducts = mapper.findById(this.customerId);
}
return customerProducts;
}

public Integer productCount(){
return getCustomerProducts().size();
}

Public Integer getCustomersTotalSpend(){
List<Products> prods = getCustomerProducts();
Integer total = 0;
if(prods.isEmpty()){
return total;
}
for(ProductModel prod : prods){
total+= prod.getValue();
}
return total;
}

}

These kind of methods are clearly tightly associated with the models data and so should never be done in the controller and even less so in the view. While the examples are a little simple and contrived, I think they highlight how you should think about your models. Having the model do as much as it can, but without stepping beyond the mark of what a model should know, provides you with the opportunity to have “Skinny controllers and Views with Fat Models”. In the above example, as long as you observe programming to an interface, you can easily swap in out models if needed without needing to change the controllers or the views and although I have written this example with Java in mind it transposes languages and is just as relevant in PHP or any other kind of language.

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha