Converting domain objects to array or json format in the view without duplicating code

In a MVC application the view is supposed to convert the data to whatever format is needed and that makes sense but this conversion logic cannot be concretely in placed in one specific view because other views will need to use it.


You can assume Views\Register and Views\Members\EditProfile will both be dealing with some sort of Entities\User object. The template only wants the data and not the behaviour of the user object so this user object needs to be converted to array format and then binded to the template.

How do you prevent this encoding/conversion process from having duplicate code? Have some sort of encoder/converter object per domain object which can get injected into views?

This would obviously work but is there a better more tested or common way that is better?


The View displays things. The View Model contains the data required by the View. Each view has its very own model and similar views will have similar models. It is code duplication but it's not the 'bad' duplication.

The purpose is to keep things clean and deocupled so you''ll have a model for each context (UI, Bl, DAL etc). Since each works with the same concepts albeit slightly diferent, most of the time thos emodels will look very similar if not identical.

Amazingly enough, this is how you should do it, because keeping things decoupled is much useful than not repeating some fields/properties. The DRY principle applies to behaviour not to fields and even then, a behaviour serves a context. Reusing a behaviour outside its context leads to muddy code, breaking the Single Responsibility Principle.

Long story short, duplicate code is bad only if the same behaviour is duplicated in the same context. In your case, you have business entities in BL and a model in UI, that is, different things in different contexts. What you need is a mapper which can copy the relevant data from one model to another. Unfortunately, I don't know one for php.

Need Your Help

Tips on building a byte protocol

communication protocols checksum byte data-transfer

I'm communicating data between devices, and I have to program the protocol as an array of bytes.