1

I create a lot of views in my work as part of the common MVC pattern applied in web frameworks like Code Igniter and Cake.

I also adhere to the following maxim as best I can: fat models and library objects doing the logic; skinny controllers responding to user actions server side; and views presenting request results and providing UI.

This leads me to a situation where a lot of views are just html, variable echos and for loops, with the accompanying mark up for css and javascript application. Nice and clear.

However, in some cases views need to be more complex. We might need to do different things based on the state of each looped item for example and sometimes this gets quite complex.

The problem with this is that the identing applied to both html and php soon gets out of sync.

A very simple example:

<ul>
   <li> ... </li>
   <li> ... </li>
   <?foreach>
       <li> ... </li>
   <?endforeach>
</ul>

We now have li elements that are at the same depth in the output document but not at the same level in the code. If we start using other control structures this can get worse:

<ul>
   <li> ... </li>
   <li> ... </li>
   <?foreach>
       <li> ... </li>
       <?if>
           <li> ... </li>
       <?endif>
   <?endforeach>
</ul>

And so on ...

Is there a well used pattern I can follow that minimises this problem even with complex views ?

4

Conditional compilation in C and C++ suffers from a similar problem: the interleaving of preprocessor directives and C/C++ code.

The usual trick there is to indent them independently of each other. A complex bit of code might look like this:

{
    ...
    {
        ...
#if A
# if B
        ...
# else
        ...
# endif
#else
        ...
#endif
    }
}

As you can see, the preprocessor directives (#if/#else/#endif) use a completely separate indentation than the code they are interleaved with (represented by ...) and even a different number of spaces per indentation level.

For your complex views, you could employ a similar strategy and indent the PHP and HTML independently of each other. You will have to decide for yourself if it improves or hinders the readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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