Any problem with using includes for everything but page-specific content? - php

I'm developing a site that's pretty lightweight on the interface and mostly database driven (equal amounts read and write). It's written in PHP and I've found the easiest way to make each page is:
Page:
<?php include("header-nav.php"); ?>
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Data Point 1</td>
<td>Data Point 2</td>
</tr>
<tr>
<td>Data Point 3</td>
<td>Data Point 4</td>
</tr>
</table>
<?php include("footer.php"); ?>
header-nav.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Welcome</title>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
</head>
<?php include("db_connect.php"); ?>
<body>
<div id="wrapper">
<h1>Welcome</h1>
<ul id="nav">
<li>Home</li>
<li>Data</li>
</ul>
footer.php:
</div>
</body>
<?php mysql_close($dbc); ?>
</html>
All of these pages by themselves are not valid and may produce errors. Working together to create a whole page, they look great.
My question is: Would this be an efficient and easy to maintain solution?
It seems that just adding a couple includes (one at the top and one at the bottom) makes sense. Especially because the site is so lightweight that I don't need a web framework. It just feels uncomfortable to create pages without starting with <html><head>...etc.

This is definitely an okay thing. I would highly recommend it. This way if you need to change the header or anything you can do so in once place easily. And the read time for hitting the file system for the include really isn't that big of a concern. So I would say that this is definitely acceptable.

"All of these pages by themselves are not valid" - I'm not sure what you mean by this. You mean a HTML Validator wouldn't pass them? Well of course not - they are fragments of pages. What matters is what the validator says when ran against the HTML the executed PHP generates.
This is one approach, and depending on the size of the problem you're tackling it's a valid one.

Yes, IMO this is a perfectly good way to do things, especially for a small site. Done it myself many times.

Get over your discomfort. Most IDEs (Dreamweaver comes to mind) actually support this way of developing sites, and will display content correctly and honor the includes if you prefer a WYSIWYG.
I develop sites using includes, like so:
site-header.inc:
require_once 'html-header.inc';
<div id="header">
/* menus, navigation, etc. */
</div>
<div class="content">
site-footer.inc:
</div>
<div id="header">
/* menus, navigation, etc. */
</div>
require_once 'html-footer.inc';
Where "html-header.inc" and "html-footer.inc" are your HTML header and footer tags and elements (title, meta, etc.). I then have functions to allow me to add CSS, JavaScript, titles, anywhere on the page, and use ob_start() and ob_end_flush() to handle these in the footer, actually. e.g.
stylesheet_register($path, $media="screen", $type="text/css");
javascript_register($path, $type="text/javascript");
title_set($title, $overwrite=true);
It your basic concept of abstraction: Don't write the same "header" and "footer" HTML code twice. Same applies to any PHP functionality which can be easily abstracted away and decoupled. Best of luck.

Related

Twig template extract a subset

Is is possibile to extract a piece of a twig template?
I need to manage a table ajax refresh, I have a twig template for example:
<html>
<body>
<table>
<thead>
<tr><th></th></tr>
</thead>
<tbody id="mypiece">
<tr><th></th></tr>
<tr><th></th></tr>
</tbody>
</table>
</body>
</html>
In the first load I need the whole template, via ajax I need just the #mypiece content, is it possibile to extract it from twig using the DOM id or with some other markers?
The only solution I found is to divide this in two different template and use an include steatment.
whole.html
<html>
<body>
<table>
<thead>
<tr><th></th></tr>
</thead>
<tbody id="mypiece">
{% include 'content.html' %}
</tbody>
</table>
</body>
</html>
content.html
<tr><th></th></tr>
<tr><th></th></tr>
But I think this is really a bad solution...
Well, I personally prefer do actually divide them, but if you intend to get something with AJAX as well - try using embeded controllers (in this case, specifically for your XHR request), for example:
<tbody id="mypiece">
{{ render(controller(
'SomeBundle:SomeController:someAction',
{ 'someParameter': "something" }
)) }}
</tbody>
This is a lot better then to parse some rendered template to get part of it, because to me it seems like design flow.
Even better solution is to return specified json data on ajax call and render it in one of the javascript template engines on the client side.
Hope this helps, cheers.

Reusable user interface in PHP?

For most of my projects I make an administration interface, which has the same design for every project. The design of the header, the footer, the topbar, the leftmenu, the css, etc. are always the same. It is a pity to create the views every time; so I was thinking: maybe there would be a nice way to put the admin interface in my MVC library, as it is reused by every project?
But for the moment, in every single view I got code like the following:
<?php $this->_include('/includes/doctype.php'); ?>
<head>
<?php $this->_include('/includes/head.php'); ?>
<title>Some title</title>
</head>
<body>
<?php $this->_include('/includes/topbar.php'); ?>
<div id="page">
<?php $this->_include('/includes/header.php'); ?>
<?php $this->_include('/includes/leftmenu.php'); ?>
<div id="content" role="main">
<h1>Some title</h1>
<p>Blah blah blah.</p>
</div><!-- /#content -->
<?php $this->_include('/includes/footer.php'); ?>
</div><!-- /#page -->
</body>
</html>
Would it be a good idea to extract the custom content from the structure of the interface, and put that structure in my library somehow to make it reusable?
After that how will it be possible to customize the title and the actual menus?
I do this all the time. I have a custom header and footer file that are called at the start and end of every page.
<?PHP
Require("includes/header.php");
...
Require("includes/footer.php");
?>
The header provides a database handle, a datetime string and handles logon, priveleges, logging of pageviews etc.
The footer provides a standard HTML page but includes some systematised variables. It also generates the menu dynamically from the driving database then closes the database connection.
This way when I write code, I don't get mixed up in the HTML and any bugs are easy to find.
I like variables akin to:
$display_scripts - adds extra data in the head section.
$display_onload_scripts - adds onload scripts to body section.
$display_style_sheets - option to include link to additional stylesheets
$display_above_menu - will appear above the menubar. NOT recommended.
$display_below_menu - will appear immediately below the menubar.
$display_one_column - page contents when only one column is to be used
$display_left_column - page contents when two columns used. Left pane.
$display_right_column - page contents when two columns used. Right pane.
$display_footer - appears in footer division.
My main code then just has to generate the appropriate variable. Fundamentally, what you need to do is examine the source of a good age you have produced then replace the stuff you want to change with variables.
Here is a schematised version of the file I use (pseudocode) to give you an idea of how I do it.
// Code here generates the menu from database
// Code here genereates popup alert messages from other users
//permanent links to external style sheets go here.
//You can also select skins here.
<?PHP
echo $display_style_sheets;
echo "<title>".$display_page_title."</title>";
?>
<script type="text/javascript" src="JAVASCRIPT GOES HERE.js"></script>
</head>
<body <?PHP echo $display_onload_scripts;?> >
<div id="page_area" >
<div id="banner">
</div>
<?php
echo $display_above_menu;
if(!$hide_menu){echo $display_menu;} //Insert the menu variable here.
echo $display_below_menu;
?>
<div id="content_area">
<div id="inner_content">
<?PHP
if($display_number_of_columns==1)
{
echo "<div id='onecolumn'>".$display_one_column."</div>"; //I only use this one
}
if($display_number_of_columns==2)
{
echo "<div id='leftcolumn'>".$display_left_column."</div>"; //these are left for legacy support from before I got better at CSS.
echo "<div id='rightcolumn'>".$display_right_column."</div>";
}
echo "<div id='footer'>".$display_footer."</div>"; //just in case - I hardly use it.
echo $display_pop_box; //for user alert messages to other users
?>
</div>
</div>
</div>
<div id="logbox"> Automatic Logout statement</div> //this is called by JS to activate timeouts.
</body>
</html>
<?PHP
$mysqlidb->close();
?>
Sorry it's such a lot of code. The layout allows easy adaptation and makes it simple to find the offending variable if things are not going as expected. There are more elegant solutions but this works well for me and is very fast.

Trouble Image Mapping In Dreamweaver

Dreamweaver is generally pretty easy to image map in but I can't seem to get the crosshairs for the image mapping tool to work. I have version CS5.5.
<html>
<head>
<div id="top-header">
<div align="center">
<table width="1000" border="0" align="center" cellpadding="0" cellspacing="0" margin="20">
<tr>
<div id="top-image"><img src="pics/TopHeader.jpg"></div>
<tr>
<div id="nav-bar"><img src="pics/NavBar.jpg" name="NavBar" border="0" usemap="#NavBarMap" id="NavBar"></div>
</div>
</div>
</div>
</table>
</head>
</html>
Basically I'm trying to just click on the NavBar.jpg file in the design window, get the rectangle mapping cursor and just start making the map. For further clarity, this is a header.inc.php file that I'm using to include in all the pages on the site. Every time I go to click on the image it highlights the table code on the split screen.
Can you not image map within a table? I'm using the table for alignment purposes so I'd like to keep it in there if possible. Thanks.
I'm not exactly sure what you are shooting for in your navigation, but you can do the whole thing with CSS in a multitude of different ways. It will be easier to create, and easier to change later on if you find that you need to.
If you haven't created navigation in css before, this list will help you cover a lot of ground: http://www.alvit.de/css-showcase/css-navigation-techniques-showcase.php
EDIT:
This site also has some excellent tutorials to clear up any confusion: http://net.tutsplus.com/?s=css+navigation

Terrible Layout - php and html/tables intermxed

I am working on a project currently where the Index.php file basically acts as a layout page and basically uses tables for the layout.
Please have a look at it's contents below. This is just a small part of the code, there's much more like this.
I need to pass on this file to a Front End Developer/ Designer so that he could change the layout as well as change the code to use CSS instead of Tables for the layout. But I think this is a mess and the designer might have issues understanding and modifying this.
What's the best way to structure and organize this code so that
1)The code becomes much more cleaner, structured and organized.
2)It's easier for the Designer to understand and change the layout.
<table width="770" border="0" cellspacing="0" cellpadding="0" align="center">
<tr><td colspan="3"><?php include("header.inc.php"); ?>
</td></tr>
<tr>
<?php
if ($xview == "main" || $show_sidebar_always)
{
?>
<td width="185" id="sidebar_left" valign="top">
<table width="90%" class="buttons" cellpadding="0" align="center">
<tr>
<td>
<!-- Begin Version 5.0 -->
<?php echo $lang['HOME_LINK']; ?>
<!-- End Version 5.0 -->
</td>
</tr>
<tr>
<td>
<?php echo $lang['POST_LINK']; ?>
</td>
</tr>
<?php if($enable_calendar) { ?>
<tr>
<td>
<?php echo $lang['POST_EVENT_LINK']; ?>
</td>
</tr>
<?php } ?>
<?php if($enable_images) { ?>
<tr>
<td>
<?php echo $lang['POST_IMG_LINK']; ?>
</td>
</tr>
<?php } ?>
<?php if($forum_dir) { ?>
<tr>
<td>
<?php echo $lang['FORUM_LINK']; ?>
</td>
</tr>
<?php } ?>
<tr>
<td>
<?php if($auth->id) { ?>
My Account
Watch List
Logout
<?php }else{ ?>
Login
Sign up
<?php } ?>
</td>
</tr>
</table>
<br>
To improve readability try using Alternative PHP Syntax in your HTML output.
<?php if($enable_calendar): ?>
...
...
<?php endif; ?>
Instead of:
<?php if($enable_calendar) { ?>
...
...
<?php } ?>
The closing blocks are a bit more intuitive than just a closing curly brace.
It would be better to let the designer create a completely new layout and then add the PHP logic into into. If you rewrite this I strongly suggest using a template engine.
Mmm. Here are some advices:
1) Use tables only when you want to show a table. Really. Almost 95% of the cases can and must be done using divs.
2) Use a template engine! so you don't mess up your html with your php code (and the designer won't break it). Good templating engines are Smarty (the most popular) and TemplatePower
Hope this helps. Cheers
I recommend you use a Template Engine, like the Smarty Template Engine
You can easily implement.
Use a templating engine like Smarty. Now if you ask around, most people hate Smarty for some reason or another, so do your research first. However it's great when you want the CSS / HTML to be in one place, and the business logic somewhere else.
Regardless of what you end up using, do a little research into the MVC design pattern -- that's a much cleaner way in general of keeping things organized.
I would first start by sorting out all the indentation, I know that's a corny thing to say, but it will be 10 times more readable than it was before you start optimising it.
<table>
<tr>
<td><?php echo "hi"; ?></td>
<td>cell 2</td>
</tr>
</table>
if you are going to intersperse <?php if(true == true) { ?> with <?php } ?> then try to make sure that they line up.
As a general rule on layout though, tables within tables is soooo 90s :P try reading up on CSS positioning using div elements and laying them out using the CSS instead of in the HTML.
I would take the time to invest your time to a CMS such as WordPress or Drupal, and learn how to apply CSS and PHP styles to the CMS. In particular, as I am familiar with WordPress, I can confidently state that developing a theme for WordPress allows you to intermingle direct PHP.
If using a CMS is not an option, then you probably should decide to create an API for your functions, create proper documentation for these API functions, and ask your developer to call off the API, for another layer of abstraction.
I do not recommend using a templating system such as Smarty, as it creates another layer of difficulty for your developers to learn. PHP as it stands is perfectly fine.

Cheap php templating with vprintf?

Ok,
so printf/sprint/vprintf all accept a certain type specifier syntax %[num][type]. (http://us2.php.net/sprintf see examples 3 and 4) Where num is the index to the type.
Example:
vprintf('Number %1$d string %2$s. String %2$s, number %1$d',array(1,"no"));
Yes, it is limited... And you would need to maintain the indexes. But it's native to the language and (i think) fast.
I just want some thoughts on how useful this would be as say a second stage to something like this: http://www.techfounder.net/2008/11/18/oo-php-templating/.
(and if anyone knows about printf/vprintf's speed that would be appreciated)
full example of what i'm talking about:
frontpage.php:
<html>
<head>
<title> %1$s </title>
</head>
<body>
Hello %2$s! You have reached page: %1$s!
</body>
</html>
whatever.php:
ob_start();
include frontpage.php;
$ob_output = ob_get_clean();
vprintf($ob_output,"Page Title","Bob");
If you want cheap PHP templating, use separate files with PHP expression blocks. It is possible to make a templating system using printf-style format strings, but there are two main problems I can see with this approach: speed and readability. The printf functions are intended for use on shorter strings, and although I don't have any statistics on hand, I think it's safe to say that running a sprintf() or a vprintf() on one huge string representing the page body will be slower than just using PHP expression blocks in a file.
That leads into the next issue: readability. Compare these two HTML templates:
<html>
<head>
<title>%s</title>
</head>
<body>
<div id="main">
<h1>%s</h1>
<p>%s</p>
</div>
<div id="other">
<p>%s</p>
</div>
<p id="footer">
%s. Took %.2f seconds to generate.
</p>
</body>
</html>
and
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<div id="main">
<h1><?= $header ?></h1>
<p><?= $body_text ?></p>
</div>
<div id="other">
<p><?= $misc_info ?></p>
</div>
<p id="footer">
<?= $copyright ?>. Took <?= $load_time ?> seconds to generate.
</p>
</body>
</html>
Or, let's say I had decided to use format strings with indexed arguments. Say, something like this:
<h1>%1$s</h1>
<p>%2$s</p>
<span id="blah">%3$s</p>
<p>%4$s</p>
<p>%5$s</p>
Now, what if I wanted to switch the ordering around?
<h1>%1$s</h1>
<p>%3$s</p>
<span id="blah">%5$s</p>
<p>%4$s</p>
<p>%2$s</p>
These are obviously contrived, but think about how it would be to maintain the printf templates in the long run.
So, in general, if you want quick-and-dirty PHP templating, use template files that contain PHP expression blocks. The printf functions are a lot better at tackling smaller string formatting tasks.
I generally have two files:
A controller of some sort (recipes.controller.php rewritten to /recipes/123)
One of many views for a controller (recipes.view.html)
I simply do all of the logic/database work within the controller and then include the appropriate view at the end. The view has access to all of the variables in the controller so I already have things like $title, $ingredients[], etc. created. I'm not really sure why people make it any more complicated than that. It's very easy to follow.
The view file will basically just look like this:
<html>
<head>
<title><?=$title ?></title>
</head>
etc...
Rasmus Lerdorf, creator of PHP, prefers to include his variables something like this:
<select class="f" name="cat" id="f_cat" size="1">
<option selected>Category</option>
<?php foreach($categories as $cat) echo <<<EOB
<option value="{$cat}">{$cat}</option>
EOB;
?>
For reference, <<<EOB through EOB; is a heredoc.
Source: The no-framework PHP MVC Framework by Rasmus Lerdorf

Categories