Separating logic in traditional PHP
Aug 14, 2006
When doing some small development projects like creating web forms for a client, I don't have the luxury of using cakePHP for the project. But after being spoiled by cake's beautiful framework, "traditional" PHP programming just seems clunky. So to help myself out and to prevent spaghetti code, I created a simple function that I include in my PHP files that allows me to have views similar to cake that work as templates. This helps promote a clear separation of processing logic and the presentation layer of my mini application. This little function really helped organize the project and I thought others might benefit from it:$data = $_POST;
$tpl = array();
function renderView($view, $noLayout = false) {
global $data, $tpl;
foreach($tpl as $key => $value) {
$$key = $value;
}
if(!$noLayout) require_once 'views/header.php';
require_once 'views/'.$view.'.php';
if(!$noLayout) require_once 'views/footer.php';
} The function relies on two variables which are used to pass values to the view. If you wish to set a value to be used within your view, inside your PHP file that does the processing, you would set the value like so: $tpl['varname'] = "value"; The renderView('path/to/view') function will automatically create a variable to be used in the view. So to call $tpl['varname'] in your view, you would simply use the variable, $varname. $data is just a convience wrapper for $_POST which would contain data from the form submittion (handy for re-displaying input when the form doesn't validate).It's straight-forward and very simple, but this little function really helps to easily create a separated application quickly. I hope someone finds a use for it
1 comment





Roy