<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP Starter &#187; Tips</title>
	<atom:link href="http://phpstarter.net/tag/tips/feed/" rel="self" type="application/rss+xml" />
	<link>http://phpstarter.net</link>
	<description>PHP Tips &#38; Tools From Starters to Experts</description>
	<lastBuildDate>Fri, 25 Jun 2010 14:14:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Separating the Application &amp; Presentation and Alternative Syntax</title>
		<link>http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/</link>
		<comments>http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 16:31:47 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=414</guid>
		<description><![CDATA[One of the biggest pet peeves I have when looking at (and unfortunately &#8211; working with) other people&#8217;s PHP code is the way they integrate their code into the HTML. Many people don&#8217;t take the time to organize, and they end up with a PHP &#038; HTML mess. I believe that it is critical to [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>One of the biggest pet peeves I have when looking at (and unfortunately &#8211; working with) other people&#8217;s PHP code is the way they integrate their code into the HTML.  Many people don&#8217;t take the time to organize, and they end up with a PHP &#038; HTML mess.  I believe that it is critical to separate the application logic from the presentation.  In other words &#8211; do the bulk of the application operations in a script file that has <strong>no text/HTML output</strong>.  When that processing is done, send the data to the presentation file that takes the data and outputs that along with the static HTML for that page.  In this article, I will present an easy way to do it using no template engines.</p>
<p><span id="more-414"></span></p>
<p>I have some perfect textbook examples that I would love to post of very badly-formatted code, but because of privacy and confidentially reasons with my clients, I can&#8217;t do that.  You will just have to take my word for it &#8211; I have seen some major hackjobs thrown together by the most obvious of n00bs I didn&#8217;t even know existed.</p>
<p>So the main thing to remember is this: Think of your web application as having two layers &#8211; <strong>application</strong> &#038; <strong>presentation</strong>.  The only job for the presentation layer is to format the data into the HTML and send it to the browser.  Everything else falls to the application layer.</p>
<h3>Bad Example</h3>
<p>I decided to write a script that would utilize a database table in my sample database.  This example uses data from the article on how to <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">Locate the Nearest Radar Station and Display Radar Images</a>.  This script will take your IP&#8217;s location, and show the 10 closest radar stations to that location &#8211; but displaying the results in way that should make you cringe.</p>
<p style="text-align: right; "><a href="/samples/414/fail.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;IP Geolocation Example&lt;/title&gt;
&lt;meta name=&quot;generator&quot; content=&quot;Bluefish 1.0.7&quot;&gt;
&lt;meta name=&quot;author&quot; content=&quot;Andrew Wells&quot;&gt;
&lt;meta name=&quot;date&quot; content=&quot;2008-12-26T17:05:21-0600&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;application/xhtml+xml; charset=UTF-8&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

echo '&lt;h2&gt;Details on IP Location:&lt;/h2&gt;';
echo '&lt;b&gt;Location ID:&lt;/b&gt; ' . $location['locId'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Country:&lt;/b&gt; ' . $location['country'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Region:&lt;/b&gt; ' . $location['region'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;City:&lt;/b&gt; ' . $location['city'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Postal Code:&lt;/b&gt; ' . $location['postalCode'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Latitude:&lt;/b&gt; ' . $location['latitude'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Longitude:&lt;/b&gt; ' . $location['longitude'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Metro Code:&lt;/b&gt; ' . $location['metroCode'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Area Code:&lt;/b&gt; ' . $location['areaCode'] . &quot;&lt;br /&gt;\n&quot;;

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 10&quot;;
$result = mysql_query($query, $db) or die(mysql_error());

echo'&lt;h2&gt;Radar Site Details&lt;/h2&gt;&lt;table width=&quot;800&quot;&gt;';
echo '&lt;tr&gt;';
echo '&lt;th&gt;Station ID&lt;/th&gt;';
echo '&lt;th&gt;Lat&lt;/th&gt;';
echo '&lt;th&gt;Lon&lt;/th&gt;';
echo '&lt;th&gt;Updated&lt;/th&gt;';
echo '&lt;th&gt;Distance&lt;/th&gt;';
echo '&lt;/tr&gt;';
for ($i = 0, $n = mysql_num_rows($result); $i &lt; $n; $i++)
{
	$radar = mysql_fetch_assoc($result);
	echo '&lt;tr&gt;';
	echo '&lt;td&gt;' . $radar['id'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['lat'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['lon'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['updated'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['distance'] . '&lt;/td&gt;';
	echo '&lt;/tr&gt;';
}
echo '&lt;/table&gt;';
?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This isn&#8217;t a worst cast scenario &#8211; I&#8217;ve seen worse, but I would like to point out the PHP code block in the middle of the header and footer HTML.  Notice all the application work I&#8217;m doing in lines 13-67 that is right in the middle of the HTML output.  Looking further, you can see that I am using echo statements to output the table HTML and other code.  This is <strong>bad</strong>.  It makes it hard to change the HTML without messing with the PHP, and it makes it next to impossible for a designer to work with it.</p>
<h3>Good Example</h3>
<p>Here is a better example with most of the logic separated from the HTML.</p>
<p style="text-align: right; "><a href="/samples/414/win.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php
/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 10&quot;;
$result = mysql_query($query, $db) or die(mysql_error());

for ($i = 0, $n = mysql_num_rows($result); $i &lt; $n; $i++)
{
	$radars[] = mysql_fetch_assoc($result);
}
?&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;IP Geolocation Example&lt;/title&gt;
&lt;meta name=&quot;generator&quot; content=&quot;Bluefish 1.0.7&quot;&gt;
&lt;meta name=&quot;author&quot; content=&quot;Andrew Wells&quot;&gt;
&lt;meta name=&quot;date&quot; content=&quot;2008-12-26T17:05:21-0600&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;application/xhtml+xml; charset=UTF-8&quot;&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h2&gt;Details on IP Location:&lt;/h2&gt;
&lt;b&gt;Location ID:&lt;/b&gt; &lt;?=$location['locId']?&gt;&lt;br /&gt;
&lt;b&gt;Country:&lt;/b&gt; &lt;?=$location['country']?&gt;&lt;br /&gt;
&lt;b&gt;Region:&lt;/b&gt; &lt;?=$location['region']?&gt;&lt;br /&gt;
&lt;b&gt;City:&lt;/b&gt; &lt;?=$location['city']?&gt;&lt;br /&gt;
&lt;b&gt;Postal Code:&lt;/b&gt; &lt;?=$location['postalCode']?&gt;&lt;br /&gt;
&lt;b&gt;Latitude:&lt;/b&gt; &lt;?=$location['latitude']?&gt;&lt;br /&gt;
&lt;b&gt;Longitude:&lt;/b&gt; &lt;?=$location['longitude']?&gt;&lt;br /&gt;
&lt;b&gt;Metro Code:&lt;/b&gt; &lt;?=$location['metroCode']?&gt;&lt;br /&gt;
&lt;b&gt;Area Code:&lt;/b&gt; &lt;?=$location['areaCode']?&gt;&lt;br /&gt;

&lt;h2&gt;Radar Site Details&lt;/h2&gt;&lt;table width=&quot;800&quot;&gt;
&lt;tr&gt;
	&lt;th&gt;Station ID&lt;/th&gt;
	&lt;th&gt;Lat&lt;/th&gt;
	&lt;th&gt;Lon&lt;/th&gt;
	&lt;th&gt;Updated&lt;/th&gt;
	&lt;th&gt;Distance&lt;/th&gt;
&lt;/tr&gt;
&lt;?php foreach ($radars as $radar): ?&gt;
&lt;tr&gt;
	&lt;td&gt;&lt;?=$radar['id']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['lat']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['lon']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['updated']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['distance']?&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;?php endforeach; ?&gt;

&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In lines 46-54, I am using PHP shorthand tags to output PHP variables in a cleaner way.  The other thing you will notice is that there is no getting around the loop structure that is needed to output the 10 radar sites.  We can do it without the curly braces though, and with neater &#8220;tags&#8221; in the HTML to control the loop.</p>
<p>Another thing to mention &#8211; I would even have the PHP block in a different file, but I combined them for the simplicity of the example.</p>
<h3>PHP Shorthand Tags and Alternative Syntax</h3>
<p>Since the presentation files are to be more focused on the HTML, and won&#8217;t be very PHP-intense, we can use simplified tags.  To output PHP variables in HTML without the PHP opening/closing tags, we use the shorthand method:</p>
<pre class="brush: php">
&lt;!-- old method --&gt;
&lt;html&gt;
&lt;?php
    echo $some_var;
?&gt;
&lt;/html&gt;

&lt;!-- better method --&gt;
&lt;html&gt;
&lt;?=$some_var?&gt;
&lt;/html&gt;
</pre>
<p>If we need to have a control structure, such as an if statement or loop, we do it this way:</p>
<pre class="brush: php">
&lt;html&gt;
&lt;?php if ($condition): ?&gt;
&lt;p&gt;Some content here&lt;/p&gt;
&lt;?php endif; ?&gt;
&lt;/html&gt;
</pre>
<p>Here is a loop example:</p>
<pre class="brush: php">
&lt;html&gt;
&lt;?php for ($i = 0; $i &lt; 10; $i++): ?&gt;
&lt;p&gt;Some content here with the current index of &lt;?=$i?&gt;&lt;/p&gt;
&lt;?php endfor; ?&gt;
&lt;/html&gt;
</pre>
<p>So there you have it &#8211; a few tips for you to create more readable code.  I have read that doing it this way with several PHP opening/closing tags can hurt performance by a hair, but I prefer losing a few CPU cycles over several hours debugging later down the road.  The choice is yours. <img src='http://phpstarter.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Omit the PHP Closing Tag</title>
		<link>http://phpstarter.net/2009/01/omit-the-php-closing-tag/</link>
		<comments>http://phpstarter.net/2009/01/omit-the-php-closing-tag/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 11:00:09 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=314</guid>
		<description><![CDATA[This is just a simple tip that presents a simple proposition &#8211; stop closing your PHP tags. Why? I will explain in this article. Keep in mind that this idea / standard only applies to PHP files that are only for PHP &#8211; no HTML. PHP developers frequently encounter the problem with sending headers and [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>This is just a simple tip that presents a simple proposition &#8211; stop closing your PHP tags.  Why?  I will explain in this article.  Keep in mind that this idea / standard only applies to PHP files that are only for PHP &#8211; no HTML.</p>
<p><span id="more-314"></span></p>
<p>PHP developers frequently encounter the problem with sending headers and cookies after output has been sent to the browser, but that problem can also happen with <strong>unintentional</strong> output.  If whitespace gets inserted after the end of a PHP code block, that can produce unintentional output when that PHP script is included.</p>
<p><strong>Solution:</strong> If that last closing tab is removed, PHP will not output that whitespace.  What I have started to do is comment the closing tag out.  This will make PHP process the whitespace instead of sending it to the browser, and since the tag is still there, you know it&#8217;s the end of the file in case it gets truncated for whatever reason.</p>
<p>If this sounds like an unusual solution, the Zend Framework makes this a requirement in their <a href="http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html">reference guide</a>.   Although they lost a bit of credit with me when I saw they require spaces over tabs. <img src='http://phpstarter.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/01/omit-the-php-closing-tag/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

