Even early on, separate out your program from your HTML!
Archive - Originally posted on "The Horse's Mouth" - 2013-04-25 18:58:34 - Graham Ellis
Even in the simplest of PHP applications, it's worthwhile to separate the validation of the incoming data from the calculations, and both of those elements from the HTML of the page itself. That means that you can use the calculation stuff - the "business logic" in other applications that use the same data, even offline ones. And it means you can change the look and feel later - or share it with your other pages / applications - easily.
Even on the first days of our PHP courses, I start to separate out the code from the view - calculating values that are to be shown on the page, storing them in variables, and the using them to fill in the view with a minimum of code. At first, the code and the view are all held in the same file (a PHP comment line of "=========" characters shows the separation), but quite quickly I'll demonstrate require and include and talk about siblings require_once and include_once.
Even though the examples that I write during a course such as the PHP Programming course I've been running this week are short, I'll ensure that the examples show a good technique for future expansion into applications of typical length.
Even though I could probably get better end-of-course reviews by sanitizing my examples, limiting what I talk about to the code in question, I choose not to do so. For I really want my delegates to leave with a knowledge and forward look which leaves them well placed to use the knowledge gained a day, a week, a month and a year after the course. Training if for the long term - and our training sets you up well for that long term.
Example inspired by a program [here] and the view it uses [here]. Run the program [here].
I have - carefully - avoided using buzzwords / buzzterms in the above, as they're not helpful to the newcomer in his / her first example. But any resemblance to Model / View / Controller is completely intentional!