How Good PHP code should be..

-separate each Web page that conforms your application in the famous 3 layers of the Web: HTML, CSS and JavaScript, for content, presentation and behavior respectively. I have a short example of how do I manage that in my PHP application.


PHP Code:
include 'lib/something_fns.php';
include 'inc/';

// put in the array the css files that you want to use
$css_files = array('reset-fonts-grids', 'default');
do_html_header('Title of your Web Page', $css_files);



// put in the array the JavaScript files that you want to use
$js_files = array('yahoo-dom-event', 'accordion');

The nice thing about the previous code is that you can achieve the separation of layers all from PHP. The separation of CSS is achieved using the function do_html_header, to this function we pass an array of css files that we want to use. In the same way, at the end of the code we put the JavaScripts files that we want to use in the function do_js_attach.
But how we can manage all these CSS and JS files with ease? and more when we have a big application to build…
Well I think an XML file could be the trick!! lets see:


<?xml version="1.0" ?>
<cssfile name="reset-fonts-grids" url="lib/yui/build/reset-fonts-grids/reset-fonts-grids.css" rel="persistent" />
<cssfile name="default" url="css/default.css" rel="preferred" />
<cssfile name="default2" url="css/default2.css" rel="alternate" />
<jsfile name="yahoo-dom-event" url="lib/yui/build/yahoo-dom-event/yahoo-dom-event.js" />
<jsfile name="accordion" url="js/accordion.js" />

So now that we have the XML file, let’s see how the function do_js_attach appends the current’s page required JS files at the end. (do_html_header works in a similar fashion)

* include the external javascript files for the current script
* @param array $js_array  the list of js files to include. Each element of the array contains one js file
function do_js_attach($js_array) {
$js_list = 'inc/conf/attach_css_js_local.xml';
if (file_exists($js_list)) {
$xml = simplexml_load_file($js_list);
} else {
exit('Failed to open xml config file'.$js_list);

foreach ($js_array as $current) {
foreach ($xml->js->jsfile as $jsfile) {
if ((string) $jsfile['name'] == $current) {
echo <<<EOB
<script src="{$jsfile['url']}"></script>


Like you see we open the XML file using PHP built in SimpleXML extension and then we loop through all the JS files and print them at the end of the Web page.

Conclusion for Structured PHP Code
I’m not sure if reading a file for every single PHP script in your application can hurt the performance (probably yes) and more when you add more CSS and JS files to the XML file, but I think is a trade-off that you probably wanted to do.**

So that’s it, maybe this trick could be useful to you and your PHP Web applications.