<?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>Think Vitamin &#187; PHP</title>
	<atom:link href="http://thinkvitamin.com/category/dev/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://thinkvitamin.com</link>
	<description>The Web Practitioner&#039;s Blog</description>
	<lastBuildDate>Thu, 09 Feb 2012 16:41:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>How to parse XML with PHP5</title>
		<link>http://thinkvitamin.com/code/how-to-parse-xml-with-php5/</link>
		<comments>http://thinkvitamin.com/code/how-to-parse-xml-with-php5/#comments</comments>
		<pubDate>Tue, 26 Jul 2011 08:42:35 +0000</pubDate>
		<dc:creator>Ray Villalobos</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Features]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=15103</guid>
		<description><![CDATA[Feeds are streams of content that people can use to share pieces of information across websites. PHP5&#8217;s simpleXML functions dramatically simplify the process of interpreting the feeds into something useful for your web pages. I recently worked on a widget that displayed a live feed of songs from one of our radio station&#8217;s playlist. The [...]]]></description>
			<content:encoded><![CDATA[<p>Feeds are streams of content that people can use to share pieces of information across websites. PHP5&#8217;s simpleXML functions dramatically simplify the process of interpreting the feeds into something useful for your web pages.<span id="more-15103"></span></p>
<p>I recently worked on a widget that displayed a live feed of songs from one of our radio station&#8217;s playlist. The system that runs our radio station outputs XML which is then fed to a database. A program turns that data into feeds that get pulled by other programs.<br />
<img src="http://i.imgur.com/Fyf9m.png" alt="Live feed from our station's playlist" /></p>
<p>It&#8217;s common to use XML to share data between servers that use different technologies. The system that generates the playlist is proprietary, so XML provides an easy format through which this data can be shared.</p>
<h3 id="what_is_xml">What is XML?</h3>
<p>The <strong>eXtensible Markup Language</strong> is a way to structure your data for sharing across sites. Some of the technologies that are crucial to the web like <strong>RSS</strong> (Real Simple Syndication) and <strong>Podcasts</strong> are special flavors of XML. The beautiful thing about XML is that you can easily roll your own for anything you need.</p>
<p>XML is easy to create because it&#8217;s a lot like HTML&#8230;except you can make up your own tags. Let&#8217;s say, for example that you&#8217;re putting together a feed for a list of songs playing at your own radio station. We&#8217;ll keep this simple, so we&#8217;ll just encode the name of the artist, the title of the song, plus the time when the song was played. We make up a couple of tags called <code>&lt;title&gt;</code> and <code>&lt;artist&gt;</code> and wrap each of them around a <code>&lt;song&gt;</code> tag. We&#8217;ll create a dateplayed attribute for each song with the date and time the song was played. You might encode something like that in this manner.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;songs<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;song</span> <span style="color: #000066;">dateplayed</span>=<span style="color: #ff0000;">&quot;2011-07-24 19:40:26&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>I left my heart on Europa<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artist<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Ship of Nomads<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artist<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/song<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;song</span> <span style="color: #000066;">dateplayed</span>=<span style="color: #ff0000;">&quot;2011-07-24 19:27:42&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Oh Ganymede<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artist<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Beefachanga<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artist<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/song<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;song</span> <span style="color: #000066;">dateplayed</span>=<span style="color: #ff0000;">&quot;2011-07-24 19:23:50&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Kallichore<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artist<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Jewitt K. Sheppard<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artist<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/song<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/songs<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>There&#8217;s some rules that you have to adhere to when creating XML data. If you&#8217;re familiar with XHTML&#8230;you&#8217;ll be right at home with some of these, but let&#8217;s review them:</p>
<ul>
<li>XML is case sensitive so <code>&lt;Title&gt;`</code> is not the same as <code>&lt;title&gt;</code>.</li>
<li>All XML elements must have closing tags.</li>
<li>XML requires a root element (the <code>&lt;songs&gt;</code> tag above serves as our root element)</li>
<li>Attributes must be quoted</li>
<li>Special characters (like &amp; <code>(&amp;amp;)</code> and &lt; <code>(&amp;lt;)</code> and &gt; <code>(&amp;gt;)</code> signs) must be encoded.</li>
</ul>
<p>XML is a bit more strict than HTML, but is real easy to create and deal with.</p>
<h3 id="introducing_simplexml">Introducing simpleXML</h3>
<p>With simpleXML, it&#8217;s as easy as reading the XML and then accessing it&#8217;s contents through an easy to read object. Assuming we&#8217;ve got our XML file above saved as a file called <code>songs.xml</code> in the same folder as our php file, we can read the whole feed into an object with the following code.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mysongs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">simplexml_load_file</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'songs.xml'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>That&#8217;s it! The file can even be the URL of a feed on the web and not just a file on your hard drive. We now have an object that is a representation of our file. The songs object has been absorbed into the <code>$mysongs</code> variable. If we want to output the name of the first artist in our list we can refer to it like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mysongs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">simplexml_load_file</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'songs.xml'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$mysongs</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">song</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">artist</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p><img src="http://i.imgur.com/8UdYw.png" alt="Showing the first artist in our XML document" /></p>
<p>Notice that our XML tags are mapped as part of the object so we can get to any element simply by typing it&#8217;s name. Remember that arrays are 0 indexed in PHP so our first title would be our 0th title. Now, let&#8217;s output the third song title.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mysongs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">simplexml_load_file</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'songs.xml'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$mysongs</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">song</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p><img src="http://i.imgur.com/TJvYf.png" alt="Showing the third song's title" /></p>
<h3 id="working_with_attributes">Working with Attributes</h3>
<p>In order to get to our dates, we&#8217;ll need to know how to access attributes, the notation is slightly different than with tags, but just as easy. As a matter of fact, it works just like accessing an array element. Let&#8217;s see how you would take a look at the second song&#8217;s date.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mysongs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">simplexml_load_file</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'songs.xml'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$mysongs</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">song</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'dateplayed'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p><img src="http://i.imgur.com/CapyG.png" alt="Showing the second song's date played" /></p>
<h3 id="making_a_list_of_songs">Making a list of songs</h3>
<p>So now that we&#8217;ve got the basics of accessing elements, let&#8217;s write the code to make a complete list of our songs parsed by interpreting our XML file.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mysongs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">simplexml_load_file</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'songs.xml'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;ul id=<span style="color: #000099; font-weight: bold;">\&quot;</span>songlist<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$mysongs</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$songinfo</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
        <span style="color: #000088;">$title</span><span style="color: #339933;">=</span><span style="color: #000088;">$songinfo</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$artist</span><span style="color: #339933;">=</span><span style="color: #000088;">$songinfo</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">artist</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$date</span><span style="color: #339933;">=</span><span style="color: #000088;">$songinfo</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'dateplayed'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;li&gt;&lt;div class=<span style="color: #000099; font-weight: bold;">\&quot;</span>title<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$title</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;&lt;/div&gt;&lt;div class=<span style="color: #000099; font-weight: bold;">\&quot;</span>artist<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;by &quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$artist</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;&lt;/div&gt;&lt;time&gt;&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$date</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;&lt;/time&gt;&lt;/li&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">endforeach</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;/ul&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>We&#8217;re using a <code>foreach</code> statement here to go through each song and then parsing the information into a simple HTML list. You can use that in a regular HTML document or use it as a widget to display a list of songs.</p>
<p><img src="http://i.imgur.com/0FzHH.png" alt="Generating a list of songs with simpleXML" /></p>
<h3 id="parsing_a_flickr_feed_from_a_set">Parsing a Flickr feed from a set</h3>
<p>There are lots of XML feeds available for you to parse online. We can, for example, get a feed from a Flickr set for inclusion on a website. That way, when you update your Flickr set, the widget will automatically display this on your site. I&#8217;ve prepared a special set with some <a href="http://www.flickr.com/photos/planetoftheweb/sets/72157627229375826/">pictures of kittens</a>. In order to get the XML for this feed, we can go to our page on Flickr and look for the XML icon at the bottom left of the screen.</p>
<p><img src="http://i.imgur.com/maGM2h.png" alt="My kittens set on Flickr " /></p>
<p>We want to examine the feed to determine it&#8217;s structure. You can right click on that feed&#8217;s link on the flickr page and save it to your hard drive, then rename the file photoset.xml and open it up with your browser.</p>
<p><img src="http://i.imgur.com/1uBoKh.png" alt="Reading the XML document" /></p>
<p>I&#8217;ve opened the XML file with Safari, which lets me take a look at the structure (Safari will normally try to push an RSS link to it&#8217;s built in reader, so saving it, giving it an XML extension and opening it will let us view the structure). I can see that each photo is stored as an <code>&lt;entry&gt;</code> tag in our XML. Inside this tag, there are two <code>&lt;link&gt;</code> tags. The first one has a link to our image on Flickr. The second one has a link to a medium sized version of our image. </p>
<p>I&#8217;m going to modify the code slightly and make an adjustment on the second link to get a small thumbnail of all of our images. Before I do that, I&#8217;ll go back to Flickr and right click on the link to the XML file and this time copy it to the clipboard, then adjust the code:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mypix</span> <span style="color: #339933;">=</span> <span style="color: #990000;">simplexml_load_file</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'http://api.flickr.com/services/feeds/photoset.gne?set=72157627229375826&amp;nsid=73845487@N00&amp;lang=en-us'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$mypix</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">entry</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$pixinfo</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
        <span style="color: #000088;">$title</span><span style="color: #339933;">=</span><span style="color: #000088;">$pixinfo</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$link</span><span style="color: #339933;">=</span><span style="color: #000088;">$pixinfo</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">link</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'href'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$image</span><span style="color: #339933;">=</span><span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;_b.jpg&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;_s.jpg&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$pixinfo</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">link</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'href'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>    
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;a href=<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$link</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;img src=<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$image</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> alt=<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$title</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> /&gt;&lt;/a&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">endforeach</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>We&#8217;re going to use the <code>&lt;title&gt;</code> tag as the <code>alt</code> text of our <code>&lt;img&gt;</code> tag. We&#8217;re also going to use the first of the <code>&lt;link&gt;</code> tags as the <code>href</code> attribute of our anchor tag. Getting to our second link will be a bit trickier. We can use the array notation to get to the second link&#8217;s href attribute (<code>$pixinfo-&gt;link[1]['href']</code>). However, that will give us a much larger picture than we&#8217;ll need. I&#8217;m using a simple <code>str_replace</code> function to change the end of our link url from _b.jpg, to _s.jpg. That will give us thumbnails, which gives you something like this.</p>
<p><img src="http://i.imgur.com/3hqQf.png" alt="The finished feed of kittens from Flickr" /></p>
<h3 id="conclusion">Conclusion</h3>
<p>SimpleXML is super easy and even fun to use to parse complicated feeds like the example from Flickr. Notice that it had no problems getting to the second instance of the <code>&lt;link&gt;</code> tag inside the <code>&lt;entry&gt;</code> tag. This would have been really difficult to do with previous versions of PHP. There&#8217;s a lot more to simpleXML, which you can read in the <a href="http://php.net/manual/en/book.simplexml.php">PHP manual</a>. If you&#8217;re interested in an object oriented approach, PHP5 also provides the <a href="http://php.net/manual/en/class.simplexmlelement.php">SimpleXMLElement</a> class.</p>
<p>If you&#8217;d like to learn more PHP, feel free to head over to the Think Vitamin Membership <a href="http://membership.thinkvitamin.com/library/php">PHP course</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/how-to-parse-xml-with-php5/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Getting started with dates in PHP</title>
		<link>http://thinkvitamin.com/code/php/getting-started-with-dates-in-php/</link>
		<comments>http://thinkvitamin.com/code/php/getting-started-with-dates-in-php/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 16:00:07 +0000</pubDate>
		<dc:creator>Ray Villalobos</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Features]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=14633</guid>
		<description><![CDATA[The date() function in PHP is powerful and complex. In this article, we’ll teach you how to get started. PHP is an amazing language. Powerful enough to be at the core of the biggest blogging platform (WordPress), deep enough to run the largest social network (Facebook) yet easy enough to be a beginner&#8217;s first server [...]]]></description>
			<content:encoded><![CDATA[<p>The date() function in PHP is powerful and complex. In this article, we’ll teach you how to get started.</p>
<p>PHP is an amazing language. Powerful enough to be at the core of the biggest blogging platform (WordPress), deep enough to run the largest social network (Facebook) yet easy enough to be a beginner&#8217;s first server side language. It&#8217;s available in even the cheapest shared hosting services and with tools like WAMP and MAMP, it&#8217;s easy to install on a local machine. The language has rich libraries of pre-built functions that make it easy for developers to get things done. A great place to get started is the rich &#8216;date&#8217; functions since working with dates is at the core of many projects.</p>
<h3 id="setting_up">Setting up</h3>
<p>PHP is a server side language, which means that unlike regular HTML, you can&#8217;t preview it in your machine&#8217;s browser by default unless you use a solution like <a href="//www.wampserver.com">WAMP</a> or <a href="http://www.mamp.info">MAMP</a> to run a a copy of the services on your machine. Before you preview these example on a browser, make sure you&#8217;ve set up a good testing environment.</p>
<p>PHP code is often embedded onto an existing HTML page which is almost always saved with a .php extension. The .php extension tells the server that it needs to process the php in the file before it sends it to the client. The client won&#8217;t see any of the PHP code, they see the results of the processed code. </p>
<h3 id="getting_a_simple_date">Getting a simple date</h3>
<p>We&#8217;re going to use the echo command to output something to our client&#8217;s browser&#8230;in this case, the date. We&#8217;ll do this in a basic page with the following code.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot; /&gt;
    &lt;title&gt;Getting started with dates in php5&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    <span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Today is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'l'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>If you&#8217;ve set things up correctly, you should see something like this on your browser:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">Today is Sunday</pre></div></div>

<p>The function outputs the text for the name of the day of the week. The date function takes at least one parameter&#8230;a string that tells the function how to format the current date.</p>
<h4 id="trying_out_different_formats">Trying out different formats</h4>
<p>If you look at the manual for the <a href="http://php.net/manual/en/function.date.php">PHP date function</a>, you&#8217;ll see that there are many ways to format dates. So, to get a date that would work as input for a MySQL database, you might use.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Today is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Y-m-d'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Which yields</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">Today is <span style="">2011</span>-06-<span style="">26</span></pre></div></div>

<p>There are some dates that are so common so there&#8217;s a few constants you can use. For example to get a date for your cookies you can use:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Today is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span>DATE_COOKIE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Which gives you something like:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">Today is Sunday, <span style="">26</span>-Jun-<span style="">11</span> <span style="">16</span>:<span style="">26</span>:<span style="">22</span> EDT</pre></div></div>

<p>Note that the quotes are gone when using constants.</p>
<h4 id="what_about_time">What about time?</h4>
<p>If you want to output the current time, you can use <code>date()</code> with a different formatting string. </p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;The time is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'g:i:sa'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Gives you:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">The time is <span style="">6</span>:06:25pm</pre></div></div>

<h4 id="localizing_your_time_zone">Localizing your time zone</h4>
<p>If you notice that the time you got back from the code above is not the right time, then more than likely, it&#8217;s due to a the fact that your server is set up for a different timezone. If you need the time to correlate to a specific location, then you can use something like this: </p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #990000;">date_default_timezone_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'America/New_York'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;The time is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'g:i:sa'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>This will set the time to Eastern Standard Time in the US. This is a <code>PHP5 function</code> (so be careful with older versions of PHP) and there are a number of strings you can use here to <a href="http://www.php.net/manual/en/timezones.php">convert the time to your local timezone</a>. If you need this on a more permanent basis, you should probably change your php.ini file.</p>
<h3 id="getting_other_dates">Getting other dates</h3>
<p>Often, you&#8217;ll need to do something with a date other than the current date. When you create a date with the <code>date()</code> function, the system uses the Unix system time, which is calculated as the number of seconds from January 1 1970 00:00:00 GMT, otherwise known as the Unix Epoch time. </p>
<p>To specify that the date function return something other than the current date, you can simply feed it the number of seconds since that date as the second parameter to the function:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Today is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Y-m-d'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1309133434</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Which results in:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">Today is <span style="">2011</span>-06-<span style="">26</span></pre></div></div>

<p>That doesn&#8217;t seem particularly useful, but it means that you can use the date functions to do calculations. But before you do that, you need an easier way to creating dates. </p>
<h4 id="creating_dates">Creating Dates</h4>
<p>There&#8217;s a couple of ways to do that. We can use the <code>mktime()</code> function to create times from a number of parameters we feed this function.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mytime</span><span style="color: #339933;">=</span><span style="color: #990000;">mktime</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">9</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">23</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">33</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">6</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">26</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2011</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Today is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Y-m-d g:i:sa'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$mytime</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>This results in the following:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">Today is <span style="">2011</span>-06-<span style="">26</span> <span style="">9</span>:<span style="">23</span>:33am</pre></div></div>

<p>You can tell from the example that the parameters you pass stand for the hour, minute, seconds, month, day and year you want to create. This is a good way of creating dates but there&#8217;s an even cooler way to do it.</p>
<h3 id="getting_a_date_from_a_string">Getting a date from a string</h3>
<p>You can use the <code>strtotime()</code> function to have php convert a human readable string to a Unix time. PHP is quite smart about converting this string to a date so you can plug in a variety of values. Here&#8217;s an easy example:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$mytime</span><span style="color: #339933;">=</span><span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;7:50pm June 26 2011&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Today is &quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Y-m-d g:i:sa'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$mytime</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Will output:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">Today is <span style="">2011</span>-06-<span style="">26</span> <span style="">7</span>:<span style="">50</span>:00pm</pre></div></div>

<p>PHP is quite clever about interpreting the string, but it&#8217;s not perfect, so make sure you test the string you put in there. This is a great way to convert MySQL or other types of strings let&#8217;s you use english-like instructions. So you can do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$nextfriday</span><span style="color: #339933;">=</span><span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;next Friday&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//next friday</span>
<span style="color: #000088;">$nextmonth</span><span style="color: #339933;">=</span><span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;+1 Month&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//On month from today</span>
<span style="color: #000088;">$lastchristmas</span><span style="color: #339933;">=</span><span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;-1 year dec 25&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//last christmas</span></pre></div></div>

<h4 id="getting_a_date_range">Getting a date range</h4>
<p>The values <code>strtotime</code> returns are converted to numbers that can be compared with simple arithmetic, so you can do interesting things with them. Let&#8217;s say, for example, that you&#8217;re teaching a class for the next 16 weeks starting next Tuesday. You&#8217;re not sure when 16 weeks from now is, plus, you&#8217;d like to get the date of each of your classes so you can start preparing your curriculum. You can do something like this.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$startdate</span><span style="color: #339933;">=</span><span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;next Tuesday&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    <span style="color: #000088;">$enddate</span><span style="color: #339933;">=</span><span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;+16 weeks&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$startdate</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//16 weeks from the starting date</span>
    <span style="color: #000088;">$currentdate</span><span style="color: #339933;">=</span><span style="color: #000088;">$startdate</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;ol&gt;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$currentdate</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$enddate</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span> <span style="color: #666666; font-style: italic;">//loop through the dates</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\t</span>&lt;li&gt;&quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'M d'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$currentdate</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;&lt;/li&gt;&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$currentdate</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;+1 week&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$currentdate</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//increment the current date</span>
    <span style="color: #b1b100;">endwhile</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// calculate date range</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;ol&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>This will show something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;"> <span style="">1</span>. Jun <span style="">28</span>
 <span style="">2</span>. Jul 05
 <span style="">3</span>. Jul <span style="">12</span>
 <span style="">4</span>. Jul <span style="">19</span>
 <span style="">5</span>. Jul <span style="">26</span>
 <span style="">6</span>. Aug 02
 <span style="">7</span>. Aug 09
 <span style="">8</span>. Aug <span style="">16</span>
 <span style="">9</span>. Aug <span style="">23</span>
<span style="">10</span>. Aug <span style="">30</span>
<span style="">11</span>. Sep 06
<span style="">12</span>. Sep <span style="">13</span>
<span style="">13</span>. Sep <span style="">20</span>
<span style="">14</span>. Sep <span style="">27</span>
<span style="">15</span>. Oct 04
<span style="">16</span>. Oct <span style="">11</span></pre></div></div>

<p>Notice this line <code>$currentdate = strtotime("+1 week", $currentdate)</code>. On this line, you can see that <code>strtotime</code> can if you specify a date number as the second parameter, <code>strtotime</code> will use than instead of the default (today) for it&#8217;s calculations.</p>
<h4 id="days_until_a_certain_date">Days until a certain date</h4>
<p>When working on a calendar, a common calculation is to find out the amount of days until a certain date. You can easily calculate the days until next thanksgiving in the US, which is on the fourth thursday in November.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> 
    <span style="color: #000088;">$someday</span><span style="color: #339933;">=</span><span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;3 weeks thursday November 1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$daysuntildate</span><span style="color: #339933;">=</span><span style="color: #990000;">ceil</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$someday</span><span style="color: #339933;">-</span><span style="color: #990000;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span><span style="color: #cc66cc;">60</span><span style="color: #339933;">/</span><span style="color: #cc66cc;">60</span><span style="color: #339933;">/</span><span style="color: #cc66cc;">24</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;There are &quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$daysuntildate</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot; until Thanksgiving&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>First, we started by calculating the thanksgiving date which was 3 weeks after the first thursday from November 1st (or the same thing as the fourth thursday). Then we used some simple arithmetic to calculate the difference between that date and the current time. When we do a comparison, we use the <code>time()</code> function because it gives us the current date in seconds from the Unix Epoch date. </p>
<p>That number is the number of seconds between those two dates. We do a simple calculation to divide that number by the minutes/hours/days (60/60/14) and we get the number of days between the two numbers. We need to use the ceil function which rounds any fractions we&#8217;re left over after our calculation.</p>
<h3 id="having_fun_with_dates">Having fun with dates</h3>
<p>If you&#8217;re just getting started with PHP, working with dates is a great way to get the feel of the language. There&#8217;s quite a lot of fun things you can do. Dig around the <a href="http://www.php.net/manual/en/refs.calendar.php">Date and Time related functions</a> in the PHP manual and share what you can do.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/php/getting-started-with-dates-in-php/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>PHP Variables and Functions Tutorial</title>
		<link>http://thinkvitamin.com/code/php/php-variables-and-functions-tutorial/</link>
		<comments>http://thinkvitamin.com/code/php/php-variables-and-functions-tutorial/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 16:01:19 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=10601</guid>
		<description><![CDATA[In this 10-minute video tutorial on PHP variables and functions, we&#8217;ll teach you the basics of variables and functions in PHP. This video is from Think Vitamin Membership, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230; Accessibility CSS3 Design Django HTML &#38; CSS HTML5 [...]]]></description>
			<content:encoded><![CDATA[<p>In this 10-minute video tutorial on <a href="http://membership.thinkvitamin.com/library/php/basics/simple-variables-and-functions?cid=106">PHP variables and functions</a>, we&#8217;ll teach you the basics of variables and functions in PHP.</p>
<p><a href="http://membership.thinkvitamin.com/library/php/basics/simple-variables-and-functions?cid=106"><img src="http://img.skitch.com/20101209-1c5nhii6q2hdaii9yee7m7mja7.jpg" alt="Screengrab of video teaching about PHP variables and functions" /></a></p>
<p>This video is from <a href="http://membership.thinkvitamin.com/?cid=106">Think Vitamin Membership</a>, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230;</p>
<ul>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106">Accessibility</a></li>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/css3/?cid=106">CSS3</a></li>
<li><a href="http://membership.thinkvitamin.com/library/css3/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/design/?cid=106">Design</a></li>
<li><a href="http://membership.thinkvitamin.com/library/design/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/django/?cid=106">Django</a></li>
<li><a href="http://membership.thinkvitamin.com/library/django/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">HTML &amp; CSS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html5/?cid=106">HTML5</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html5/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106">JavaScript</a></li>
<li><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106">jQuery</a></li>
<li><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106">NoSQL</a></li>
<li><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/php/?cid=106">PHP</a></li>
<li><a href="http://membership.thinkvitamin.com/library/php/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106">Ruby</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106">Ruby on Rails</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">SASS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ux/?cid=106">UX</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ux/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/version-control?cid=106">Version Control</a></li>
<li><a href="http://membership.thinkvitamin.com/library/wordpress?cid=106">WordPress Theme Design</a></li>
</ul>
<p>10 new videos are added every week, so it&#8217;s a great way to stay up-to-date on all the latest technology and methods. Browse the entire <a href="http://membership.thinkvitamin.com/library/?cid=106">library of videos</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/php/php-variables-and-functions-tutorial/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>PHP Password Hashing Tutorial</title>
		<link>http://thinkvitamin.com/code/php/php-password-hashing-tutorial/</link>
		<comments>http://thinkvitamin.com/code/php/php-password-hashing-tutorial/#comments</comments>
		<pubDate>Wed, 05 Jan 2011 16:00:36 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=10575</guid>
		<description><![CDATA[In this 8-minute video tutorial on PHP Password Hashing, you&#8217;ll learn how to improve your authentication code by taking passwords out of cleartext. This video is from Think Vitamin Membership, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230; Accessibility CSS3 Design Django HTML &#38; [...]]]></description>
			<content:encoded><![CDATA[<div>
<p>In this 8-minute <a href="http://membership.thinkvitamin.com/library/php/authentication/password-hashing?cid=106">video tutorial on PHP Password Hashing</a>, you&#8217;ll learn how to improve your authentication code by taking passwords out of cleartext.</p>
<p><a href="http://membership.thinkvitamin.com/library/php/authentication/password-hashing?cid=106"><img src="http://img.skitch.com/20101209-bgiexi85ww2e7temw9qeg4rrqi.png" alt="Screengrab of video on PHP Password Hashing" /></a></p>
<p>This video is from <a href="http://membership.thinkvitamin.com/?cid=106">Think Vitamin Membership</a>, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230;</p>
<ul>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106">Accessibility</a></li>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/css3/?cid=106">CSS3</a></li>
<li><a href="http://membership.thinkvitamin.com/library/css3/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/design/?cid=106">Design</a></li>
<li><a href="http://membership.thinkvitamin.com/library/design/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/django/?cid=106">Django</a></li>
<li><a href="http://membership.thinkvitamin.com/library/django/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">HTML &amp; CSS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html5/?cid=106">HTML5</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html5/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106">JavaScript</a></li>
<li><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106">jQuery</a></li>
<li><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106">NoSQL</a></li>
<li><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/php/?cid=106">PHP</a></li>
<li><a href="http://membership.thinkvitamin.com/library/php/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106">Ruby</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106">Ruby on Rails</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">SASS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ux/?cid=106">UX</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ux/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/version-control?cid=106">Version Control</a></li>
<li><a href="http://membership.thinkvitamin.com/library/wordpress?cid=106">WordPress Theme Design</a></li>
</ul>
<p>10 new videos are added every week, so it&#8217;s a great way to stay up-to-date on all the latest technology and methods. Browse the entire <a href="http://membership.thinkvitamin.com/library/?cid=106">library of videos</a>.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/php/php-password-hashing-tutorial/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>PHP form validation tutorial</title>
		<link>http://thinkvitamin.com/code/php-form-validation/</link>
		<comments>http://thinkvitamin.com/code/php-form-validation/#comments</comments>
		<pubDate>Thu, 25 Nov 2010 14:47:12 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=9366</guid>
		<description><![CDATA[In this 9-minute PHP form validation tutorial video, we add validation to our registration form. We validate name, email, and password, as well as display error messages to the user. This video is from Think Vitamin Membership, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics [...]]]></description>
			<content:encoded><![CDATA[<p>In this 9-minute <a href="http://membership.thinkvitamin.com/library/php/phpmysql-user-system/validation?cid=106">PHP form validation tutorial video</a>, we add validation to our registration form. We validate name, email, and password, as well as display error messages to the user.</p>
<p><a href="http://membership.thinkvitamin.com/library/php/phpmysql-user-system/validation?cid=106"><img src="http://img.skitch.com/20101124-r5sanmbwq3xwa5j66kgr15r3uf.png" alt="Screengrab of video" /></a></p>
<p>This video is from <a href="http://membership.thinkvitamin.com/?cid=106">Think Vitamin Membership</a>, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230;</p>
<ul>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106">Accessibility</a></li>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/css3/?cid=106">CSS3</a></li>
<li><a href="http://membership.thinkvitamin.com/library/css3/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/design/?cid=106">Design</a></li>
<li><a href="http://membership.thinkvitamin.com/library/design/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/django/?cid=106">Django</a></li>
<li><a href="http://membership.thinkvitamin.com/library/django/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">HTML &amp; CSS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html5/?cid=106">HTML5</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html5/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106">JavaScript</a></li>
<li><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106">jQuery</a></li>
<li><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106">NoSQL</a></li>
<li><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/php/?cid=106">PHP</a></li>
<li><a href="http://membership.thinkvitamin.com/library/php/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106">Ruby</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106">Ruby on Rails</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">SASS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ux/?cid=106">UX</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ux/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/version-control?cid=106">Version Control</a></li>
</ul>
<p>10 new videos are added every week, so it&#8217;s a great way to stay up-to-date on all the latest technology and methods. Browse the entire <a href="http://membership.thinkvitamin.com/library/?cid=106">library of videos</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/php-form-validation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Twitter @Anywhere Revisited</title>
		<link>http://thinkvitamin.com/code/twitter-anywhere-revisited/</link>
		<comments>http://thinkvitamin.com/code/twitter-anywhere-revisited/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 14:00:01 +0000</pubDate>
		<dc:creator>Richard Shepherd</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=7200</guid>
		<description><![CDATA[I must be honest, I was pretty unimpressed with Twitter @Anywhere when it first launched earlier this year. Of course I hadn’t bothered to check it out, but it seemed like ‘Integration Lite’ &#8211; just a very simple way for bloggers to include Twitter on their site. As Wired reported back in March Twitter’s Evan [...]]]></description>
			<content:encoded><![CDATA[<p>I must be honest, I was pretty unimpressed with <a href="http://dev.twitter.com/anywhere" target="_blank">Twitter @Anywhere</a> when it first launched earlier this year. Of course I hadn’t bothered to check it out, but it seemed like ‘Integration Lite’ &#8211; just a very simple way for bloggers to include Twitter on their site.</p>
<p>As <a href="http://www.wired.com/epicenter/2010/03/sxsw-twitter-ceo-evan-williams-launches-anywhere/" target="_blank">Wired reported back in March</a> Twitter’s Evan Williams promised <tt>@Anywhere</tt> would “reduce friction.”</p>
<blockquote><p>“You could be reading your favourite columnist [and] you can easily tweet from the column itself if […] you may just want to follow the columnist […] without going back to Twitter.”</p></blockquote>
<p>Amongst the launch partners for <tt>@Anywhere</tt> were <a href="http://digg.com/" target="_blank">Digg</a>, <a href="http://www.huffingtonpost.com/" target="_blank">Huffington Post</a> and <a href="http://www.nytimes.com/" target="_blank">The New York Times</a>. And one of the most high profile users the little known <a href="http://followfinder.googlelabs.com/" target="_blank">Follow Finder</a> from The Mighty Google.</p>
<p style="text-align: center;"><a href="http://www.followfinder.googlelabs.com/"><img class="size-medium wp-image-7201  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/followfinder.png" alt="" width="470" /></a></p>
<p>But alas, it was more a fizzle than a firework and like many at the time I was rather nonplussed.</p>
<p>I’m pleased to say I’ve been completely converted. Not only is playing with Twitter inherently a cool thing to do, it can add real power to your website and more importantly your web applications. Indeed, it’s the scope for easily including Twitter functionality in web applications that’s really exciting.</p>
<p>So let’s take a look at some of this functionality and how you can use it. You’ll be up and running in just minutes, and after briefly looking at some of the simpler methods we’ll dive straight in to integrating Twitter right into your web app.<span id="more-7200"></span></p>
<h3>Registering for @Anywhere</h3>
<p>The first thing you need to do is register for an Application ID. It’s ridiculously simply to get, but perhaps worth some explaining to the uninitiated. First head on over to <a href="http://dev.twitter.com/anywhere" target="_blank">http://dev.twitter.com/anywhere</a> and click on the &#8216;Start using it now&#8217; button.</p>
<p style="text-align: center;"><a href="http://dev.twitter.com/anywhere"><img class="size-medium wp-image-7205  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/anywherehomepage.png" alt="" width="470" /></a></p>
<p>You’ll be swiftly taken to a one-page form where you register your app. The first question, particularly to those new at this whole API game, is ‘what if I don’t have an app?’.</p>
<p>Let’s say you just want to use hovercards on your blog. Or let’s say you want your users to be able to tweet about your blog articles by providing them a tweet box at the footer of each page. Not really an ‘app’ is it? More of a feature, a widget perhaps.</p>
<p>Well, in the big wide world of APIs what you have is a web app my friend and you need to accept it! Even the humble ‘Linkify’ method (automatically turning all Twitter usernames into links to their profiles) makes your humble blog post a web application of sorts. Deal with this fuzzy distinction and move on. We need that app ID!!</p>
<p><em><strong>NB:</strong> For the rest of this article I’ll use the term app/application, but it equally applies to your site/blog</em></p>
<h3>Completing the Form</h3>
<p><strong>Application Name</strong></p>
<p>Name your application wisely because users will see this name when they are asked to authorise your app; although it’s worth noting that certain functionality, like linkifying and hovercards, doesn’t require users to see this name.</p>
<p><strong>Callback URL</strong></p>
<p>If you intend to use some of the <tt>@Anywhere</tt> functionality which requires users to authenticate your app then Twitter needs to know which page to send the API response to (which includes lots of handy data about the user that we can tap into using JavaScript!). The callback URL is most likely the very same page that has called the authentication.</p>
<p style="text-align: center;"><a href="http://dev.twitter.com/anywhere/apps/new"><img class="size-medium wp-image-7210  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/register.png" alt="" width="470"  /></a></p>
<p>If you’re only using simple <tt>@Anywhere</tt> methods like linkify you can just put your site’s homepage in here.</p>
<p><strong>Default Access Type</strong></p>
<p>This defaults to Read-only, but we want to use some advanced <tt>@Anywhere</tt> methods so make sure you change this to Read &amp; Write.</p>
<h3>Basic functions</h3>
<p>Okay, we’ve filled up this car with petrol/gas so it’s time to take it out for a spin! Open a new HTML document and in the <tt>&lt;head&gt;</tt> of the document include the following line of code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;http://platform.twitter.com/anywhere.js?id=YOUR-APP-ID-GOES-HERE&amp;v=1&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Don&#8217;t forget to add your app ID into the URL.</p>
<p>Before I go on I feel I must address those of you who now resemble Yosamite Sam, with steam coming out of their ears at the idea of ever including a JavaScript file at the top of a page. But including the <tt>anywhere.js</tt> file in the head makes a lot of sense for a number of reasons, outlined by Twitter themselves:</p>
<ul>
<li>It’s small. Less than 3kb to be exact, gzipped up into a tiny package.</li>
<li>All dependencies for <tt>@Anywhere</tt> features are loaded asynchronously, so you only get what you need when you need it.</li>
<li>Most importantly, when a user logs in and authenticates your app the Twitter login page redirects back to the callback URL. This happens in a pop-up window, so if anywhere.js is at the bottom of the page it’ll mean that the user sees your site in that pop-up before it disappears. Which looks bad and, as Twitter put it, ‘is a poor user experience’.</li>
</ul>
<p>So leave it in the <tt>&lt;head&gt;</tt> and let’s move on. Now we need to initialise the a global <tt>@Anywhere</tt> object which we do with:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>For those who have tried to run that script, you’ll see that nothing happens. That’s because we need to give it a callback function of some sort. For example, to linkify every Twitter username on a page you simply need:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T.<span style="color: #660066;">linkifyUsers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>What’s with the capital ‘T’? Well that’s just Twitter’s convention so we’ll stick with it, but you’re welcome to change it to a more descriptive name. An instance of the API client is passed into T for us to then call methods on, just as we’ve done above.</p>
<p>Run that puppy on a page which has a username in the markup and watch it magically turn into a link. It was roughly about now that I gave up on <tt>@Anywhere</tt> earlier this year, but stick with me here &#8211; it get’s better.</p>
<h3>Hovercards</h3>
<p>Another method that works in a similar way is Hovercards, which work in the same way.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T.<span style="color: #660066;">hovercards</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p><img class="aligncenter size-full wp-image-7225" src="http://thinkvitamin.com/wp-content/uploads/2010/08/hovercard2.png" alt="" width="313" height="271" /></p>
<p>With linkifying and hovercarding under our belts its worth looking at another couple of handy features.</p>
<h3>Scope</h3>
<p>You can limit the scope of a method by passing in a CSS selector. A lot of you will spot that this looks a lot like jQuery and that’s because it’s using the same <a href="http://sizzlejs.com/" target="_blank">Sizzle</a> selection engine.</p>
<p>For example, to linkify usernames only in the DIV with an ID of ‘sidebar’ you could use the following code</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span>‘#sidebar’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">linkifyUsers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<h3>Configuration Options</h3>
<p>There are a number of option that we can pass to these methods, which we do in an object literal. Again, if you&#8217;ve used jQuery before then this will be nothing new to you:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span>‘#sidebar’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">hovercards</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> expanded<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Adding <tt>{expanded: true}</tt> does exactly what it says &#8211; it renders the Hovercard in it&#8217;s expanded form from the off, rather than waiting for the user to click &#8216;more&#8217;.</p>
<h3>Moving Swiftly On</h3>
<p>I’m going to skip a bit here, which relates to some of the other configuration options you can use with the various &#8220;Anywhere methods. I highly recommend Twitter’s own documentation which you can find at <a href="http://dev.twitter.com/anywhere/begin" target="_blank">http://dev.twitter.com/anywhere/begin</a>.</p>
<h3>Getting more Advanced</h3>
<p>If you’ve spent much time surfing the interweb you’ve at some point seen that pop-up window asking you if you authorise an app or a site to play with your Twitter account. </p>
<p>If, like me, you blindly click yes you give that site direct access to lots of your personal (albeit public) information. Normally this isn’t a problem, but with great power comes great responsibility &#8211; as James Cunningham of <a href="http://twifficiency.com/" target="_blank">Twifficiency</a> fame (more at <a href="http://techcrunch.com/2010/08/17/twifficiency/" target="_blank">TechCrunch</a>).</p>
<p><img class="aligncenter size-medium wp-image-7211" src="http://thinkvitamin.com/wp-content/uploads/2010/09/authorise.png" alt="" width="470" height="" /></p>
<p>There are a couple of ways <tt>@Anywhere</tt> uses this connectivity. The first is with built in functions like the Tweet Box and the Follow button. Both need the user to login to Twitter and authorise your app, so both will cause the authorisation pop-up. We can call both like so:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#follow-button'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">followButton</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;richardshepherd&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
T<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#tweet-box'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">tweetBox</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>This places a follow button in the element with an ID of &#8216;follow-button&#8217; (and which is set to follow my Twitter account!), and a tweetbox in the element with an ID of &#8216;tweet-box&#8217;.</p>
<p><img class="aligncenter size-medium wp-image-7234" src="http://thinkvitamin.com/wp-content/uploads/2010/08/tweetbox-300x77.jpg" alt="" width="300" height="77" /></p>
<p>You’ll can find further details of the Tweet Box and Follow Buttons in the <a href="http://dev.twitter.com/anywhere/begin" target="_blank">official documentation</a>, but I think it get’s much more exciting to look at connecting your app with someone’s Twitter account and pulling information from their public profile. So let’s go ahead and crank things up! It’s surprisingly simple.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span>‘#connect’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">connectButton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> size<span style="color: #339933;">:</span> “medium” <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>And that’s it. Try it out, and you’ll see the familiar pop-up asking for you to authorise your app (the name you gave it when you signed up). You can change the size be replacing ‘medium’ with ‘small’, ‘large’ or ‘xlarge’.</p>
<p style="text-align: center;"><img class="size-full wp-image-7214  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/08/connectwtwitter.png" alt="" width="256" height="50" /></p>
<p>Medium is the default, so if you’re happy with that you can remove it from the code. But how about your own custom connect button &#8211; how cool would that be? It turns out that the Twitter API has a <tt>signIn</tt> method which we can attach to any element: text, image or whatever you fancy.</p>
<p>Let’s say you have created your own CSS rollover button, applied to a span with and ID of twitterLogin. Here’s how you’d use JavaScript and the Twitter API to hook the signIn method to that span:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span>‘twitterLogin’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">onclick</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T.<span style="color: #660066;">signIn</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>We are now freed from the shackles of Twitter’s own graphics and buttons, which makes it possible to create a unique experience for your own app or site. If the user is logged in, the pop-up window will simply ask them to authorise your app. If they aren’t logged in to Twitter it will also ask them for their login details.</p>
<h3>I Can Haz your Details?</h3>
<p>So your web app now has a connect button, and let’s assume your user has clicked it and logged in/authorised your app. Sweet. What next?</p>
<p>You should have set the Twitter callback URL to the same page as your web app, which means the pop-up will disappear and your page will be sent a bunch of new data (think of it as an AJAX request and response). This means you can use Javascript to check if the user is connected with the rather handy <tt>isConnected</tt> method. And, assuming it’s all gone to plan, the <tt>currentUser</tt> property contains lots of handy information.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>T.<span style="color: #660066;">isConnected</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #006600; font-style: italic;">// This user is connected. Awesome!</span>
<span style="color: #003366; font-weight: bold;">var</span> user <span style="color: #339933;">=</span> T.<span style="color: #660066;">currentUser</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> screenName <span style="color: #339933;">=</span> user.<span style="color: #660066;">data</span><span style="color: #009900;">&#40;</span>‘screen_name’<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>‘Hi there ‘ <span style="color: #339933;">+</span> screenName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
<span style="color: #006600; font-style: italic;">// the user isn’t connected, so probably best to show them</span>
<span style="color: #006600; font-style: italic;">// a connect button!</span>
T<span style="color: #009900;">&#40;</span>‘#twitterLogin’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">connectButton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Admittedly the use of a JavaScript alert here is almost criminal, but you get the idea. Include jQuery and you can start injecting the DOM with lots of Twitter goodness, personalising the user’s experience.</p>
<p>So what other properties can we access, apart from Screen Name? Well, pretty much all of the user’s public profile information is up for grabs. Here are some of the most useful:</p>
<ul>
<li>description</li>
<li> followers_count</li>
<li> following</li>
<li> profile_image_url</li>
<li> location</li>
<li> name</li>
<li> time_zone</li>
</ul>
<p>And you can check out a full like at <a href="http://dev.twitter.com/anywhere/begin#user-properties" target="_blank">http://dev.twitter.com/anywhere/begin#user-properties</a></p>
<p>So using our example above you could access the profile image with:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> imageHTML <span style="color: #339933;">=</span> ‘<span style="color: #339933;">&lt;</span>img src<span style="color: #339933;">=</span>”’ <span style="color: #339933;">+</span> user.<span style="color: #660066;">data</span><span style="color: #009900;">&#40;</span>‘profile_image_url’<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> ‘“ <span style="color: #339933;">/&gt;</span>’<span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>What Next?</h3>
<p>Of course <tt>@Anywhere</tt> is no substitute for server side integration with the Twitter API, but it’s a lean way of enhancing your web app/web sites experience for Twitter users.</p>
<p>Have you started to use <tt>@Anywhere</tt>? If so, tell us how and whether you think it’s enhanced your web application or site. And which features would you like to see in <tt>@Anywhere</tt> in future releases?</p>
<h3>Further reading</h3>
<p>Have you been bitten by the <tt>@Anywhere</tt> bug? If so, here are some great places to find out more…</p>
<p style="text-align: center;"><a href="http://code.google.com/p/twitter-api/issues/list"><img class="size-medium wp-image-7215  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/googlecode.png" alt="" width="470" /></a></p>
<ul>
<li><a href="http://www.slideshare.net/toddkloots/anywhere/">http://www.slideshare.net/toddkloots/anywhere/</a></li>
<li><a href="http://platform.twitter.com/js-api.html">http://platform.twitter.com/js-api.html</a></li>
<li></li>
</ul>
<p>I also really like this integration of Twitter Hovercards into a WordPress blog comments</p>
<ul>
<li><a href="http://www.binarymoon.co.uk/2010/05/integrate-twitters-wordpress-comments/">http://www.binarymoon.co.uk/2010/05/integrate-twitters-wordpress-comments/</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/twitter-anywhere-revisited/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>OOP with PHP: Finishing Touches</title>
		<link>http://thinkvitamin.com/code/oop-with-php-finishing-touches/</link>
		<comments>http://thinkvitamin.com/code/oop-with-php-finishing-touches/#comments</comments>
		<pubDate>Thu, 05 Aug 2010 09:21:11 +0000</pubDate>
		<dc:creator>Lorna Jane Mitchell</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=6788</guid>
		<description><![CDATA[This article is the last entry in the series of posts about using PHP 5 with object-oriented programming. The series began with an introduction, followed by some more advanced concepts. We then looked specifically at the magic methods in PHP and how Exceptions work. Today we&#8217;ll take a tour of some of the advanced concepts [...]]]></description>
			<content:encoded><![CDATA[<p>This article is the last entry in the series of posts about using PHP 5 with object-oriented programming. The series began with an <a href="http://thinkvitamin.com/dev/getting-started-with-oop-php5/">introduction</a>, followed by some <a href="http://thinkvitamin.com/dev/getting-started-with-oop-php5-part-2/">more advanced concepts</a>. We then looked specifically at the <a href="http://thinkvitamin.com/dev/9-magic-methods-for-php/">magic methods</a> in PHP and how <a href="http://thinkvitamin.com/dev/exception-handling-in-php5/">Exceptions </a>work. </p>
<p>Today we&#8217;ll take a tour of some of the advanced concepts that we haven&#8217;t covered yet, and this will give you a complete toolbox for working with OOP using PHP.<span id="more-6788"></span></p>
<h3>Autoloading</h3>
<p>This is a very key concept for actually using classes in PHP 5. Autoloading is a mechanism where you can specify where the code should look for a class name that follows a particular pattern. Once you have set this up, usually very early in the script when everything gets configured, then you can simply instantiate classes without having to expressly include their declaration files.</p>
<p>The <tt><a href="http://php.net/manual/en/language.oop5.autoload.php">autoload()</a></tt>function takes the name of the class and attempts to guess where to look for it, and it is common to split names by an underscore, which is why you see so many PHP classes with crazy long names like <tt>Zend_Auth_Adapter_DbTable</tt> &#8211; each underscore is a directory level, so this class declaration would be found in a file named <tt>DbTable.php</tt> in the Zend/Auth/Adapter directory.</p>
<p>To declare our own autoload function, we would do something like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> __autoload<span style="color: #009900;">&#40;</span><span style="color: #000088;">$classname</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$path</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'_'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">DIRECTORY_SEPARATOR</span><span style="color: #339933;">,</span> <span style="color: #000088;">$classname</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.php'</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">require_once</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$path</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$class</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> My_Example_Penguin<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>All our function does is replace the _ with the relevant directory separators, add a .php and then require the file. We could do much more complicated things here though, such as use a regex to check for different prefixes, add a library directory, whatever we need to. We can then load any of our classes that match the structure from anywhere in our code once we have declared the autoload &#8211; very handy!</p>
<h3>Interfaces</h3>
<p>Now that we can load our class definitions from any context in our application, this seems like an ideal time to discuss another advanced feature of OOP &#8211; <a href="http://php.net/manual/en/language.oop5.interfaces.php">Interfaces</a>. </p>
<p>PHP does not have multiple inheritance, so each object can only have one parent, and the top-level parent of all objects is of type <tt>StdClass</tt>. However PHP does support interfaces, which allows polymorphism (one class which can look like another) in PHP. </p>
<p>Let&#8217;s start off straight away by looking at an example and how the syntax works:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">interface</span> Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Sheep implements Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;baaa!&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$sheep</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Sheep<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$sheep</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>In this example, we first declared our interface Audible, with a single method called speak(). This behaves like an abstract method &#8211; we can prototype it here but we must declare it in any class which implements this interface. If we don&#8217;t, we get an error just as we did with the abstract classes we saw in an earlier post in this series. When we call <tt>$sheep-&gt;speak()</tt> at the end of the script, we see the output &#8220;baaa!&#8221;</p>
<p><a href="http://www.flickr.com/photos/lornajane/4828143200/" title="Sheep by LornaJane.net, on Flickr"><img src="http://farm5.static.flickr.com/4135/4828143200_8afc9d1379.jpg" width="470" height="" alt="Sheep" style="border: 1px solid #CCC;" /></a></p>
<p>An important thing to note about interfaces is that it allows us to specify a subset of behaviours and then apply them to objects that need not necessarily be related to one another by inheritance. We can use interfaces to check than an object is capable of what we are about to ask it to do, before we actually do it. </p>
<p>Keeping with the noisy animals examples, consider this example containing the same interface as before with some additional animals.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">interface</span> Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Sheep implements Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;baaa!&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Fish <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Dog implements Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;woof woof!&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$sheep</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Sheep<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$sheep</span> instanceOf Audible<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$sheep</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;*stares blankly*&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Notice here we&#8217;re using the <tt>instanceO</tt>f to check the type of the object. This will return true if the Object passed in is either the same type as the class name, a child type of that class, or if it or any of its parents implement the class name as an interface. This means that although our <tt>$sheep</tt> is of type Sheep, it will also appear to be of type Audible.</p>
<p>In the code example, our Sheep does implement the Audible interface, as does the dog so either of those animals would speak. If we instantiated a fish though, this does not implement Audible and so we would fall through to the other part of the conditional and see the output *stares blankly&#8221; &#8230; which sounds about right for a fish!</p>
<p>It is also worth noting that if, for example, the dog did have a method called <tt>speak()</tt> but was not declared to implement the Audible interface, it would fail the type check and the dog would then also stare blankly, so to speak.</p>
<h3>Type Hinting</h3>
<p>In the example above, we used the <tt><a href="http://php.net/manual/en/language.operators.type.php">instanceOf</a></tt> comparison operator to check that an object with the correct capabilities had been received, but we can make this simpler by using type hinting in our functions and object methods. We can adapt the earlier example to illustrate how this works, like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">interface</span> Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Sheep implements Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;baaa!&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Fish <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Dog implements Audible <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;woof woof!&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> makeHeard<span style="color: #009900;">&#40;</span>Audible <span style="color: #000088;">$animal</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$animal</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
makeHeard<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Sheep<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
makeHeard<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Dog<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
makeHeard<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Both sheep and dog speak as expected, but the fish causes PHP to throw errors since we did not pass the correct Object type. Type hinting is a very powerful tool in OOP, in all reusable code but especially when creating libraries or frameworks. </p>
<p>By specifying what kind of an object is expected, you can protect against mis-use of the function. This is less about controlling what people do with your precious code and more about making it clear what the method was expecting to receive, in object type and/or in the capabilities of the incoming item.</p>
<h3>Fluent Interfaces</h3>
<p>This is a neat trick that can often be seen in particular in framework code, so it is worth a mention here. A &#8220;fluent interface&#8221; is one where you can chain the methods together, useful especially where you would be calling a sequence of methods on the same object. </p>
<p>For this to work, each method to be chained needs to return the object it belongs to, so a class would look something like this (a jumper, the obvious progression from a sheep):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Jumper <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setSize<span style="color: #009900;">&#40;</span><span style="color: #000088;">$size</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$size</span> <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">8</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000088;">$size</span> size <span style="color: #339933;">=</span> <span style="color: #000088;">$size</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> fold<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// fold the jumper</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> sell<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sold</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>We could interact with our class using code that looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$blue_jumper</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Jumper<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$blue_jumper</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setSize</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">12</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$blue_jumper</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">fold</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$blue_jumper</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sell</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>But with the fluent interface in place, we can alternatively do exactly the same thing using the method chaining:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$blue_jumper</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Jumper<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$blue_jumper</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setSize</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">12</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">fold</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sell</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>You&#8217;ll often see this notation used in settings such as the database interfaces in frameworks (both<a href="http://framework.zend.com/"> Zend Framework</a> and <a href="http://codeigniter.com/">CodeIgniter</a> spring to mind) and really anywhere else where you could be calling multiple methods on the same object in quick succession. Hopefully this makes it clear what is going on when you see all those arrows in a row!</p>
<h3>Parting Thoughts on OOP and PHP</h3>
<p>We&#8217;ve been through a whole host of OOP concepts in PHP, illustrating that the object model in PHP has much more functionality than the urban myths would have you believe. (In the defence of urban myths, when PHP first got &#8220;objects&#8221; in PHP 4, the result was neither pretty or complete, so there was some truth to that rumour 5+ years ago!)  </p>
<p>This series of articles has been intended to give a good overview of the main features along with some examples on actually using these in your own applications and working with them when you see them in the wild. </p>
<p>If you&#8217;re still hungry for more then some interesting next topics would be <a href="http://uk2.php.net/manual/en/book.reflection.php">reflection</a> and the <a href="http://uk2.php.net/manual/en/book.spl.php">SPL extension</a> in PHP &#8211; both give opportunities for doing some very nice tricks with PHP and objects. </p>
<p>If you are using objects, share your applications and ideas with us in the comments, we love to hear what you think of our posts and for you to share what you are building with these techniques!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/oop-with-php-finishing-touches/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>PHP Login Form Part 1 [Video Tutorial]</title>
		<link>http://thinkvitamin.com/code/php-login-form-part-1-video-tutorial/</link>
		<comments>http://thinkvitamin.com/code/php-login-form-part-1-video-tutorial/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 11:00:41 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=6780</guid>
		<description><![CDATA[For our second free weekly helping from the Think Vitamin Membership video library Jim looks at how to create the perfect login form using PHP. Don&#8217;t forget to check out the video library for free videos as well as learning more about our new membership service.]]></description>
			<content:encoded><![CDATA[<p>For our second free weekly helping from the <a href="http://membership.thinkvitamin.com/">Think Vitamin Membership</a> video library Jim looks at how to create the perfect <a href="http://membership.thinkvitamin.com/library/php/authentication/log-in-form-part-1/">login form using PHP</a>. </p>
<p>Don&#8217;t forget to check out the video library for free videos as well as learning more about <a href="http://membership.thinkvitamin.com/">our new membership service</a>.<br />
<!-- Start of Brightcove Player --></p>
<div style="display:none">
</div>
<p><!--<br />
By use of this code snippet, I agree to the Brightcove Publisher T and C<br />
found at https://accounts.brightcove.com/en/terms-and-conditions/.<br />
--></p>
<p><script language="JavaScript" type="text/javascript" src="http://admin.brightcove.com/js/BrightcoveExperiences.js"></script></p>
<p><object id="myExperience260913905001" class="BrightcoveExperience"><param name="bgcolor" value="#FFFFFF" /><param name="width" value="705" /><param name="height" value="388" /><param name="playerID" value="89176682001" /><param name="playerKey" value="AQ%2E%2E,AAAAFEediwk%2E,2euW9ZlTxZAx4lLOZ1DtKcbmqEvxwq5q" /><param name="isVid" value="true" /><param name="isUI" value="true" /><param name="dynamicStreaming" value="true" /><param name="@videoPlayer" value="260913905001" /></object></p>
<p><!--<br />
This script tag will cause the Brightcove Players defined above it to be created as soon<br />
as the line is read by the browser. If you wish to have the player instantiated only after<br />
the rest of the HTML is processed and the page load is complete, remove the line.<br />
--><br />
<script type="text/javascript">brightcove.createExperiences();</script></p>
<p><!-- End of Brightcove Player --></p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/php-login-form-part-1-video-tutorial/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PHP Basics: Installation [Video Tutorial]</title>
		<link>http://thinkvitamin.com/code/php-basics-installation-video-tutorial/</link>
		<comments>http://thinkvitamin.com/code/php-basics-installation-video-tutorial/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 10:21:48 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=6776</guid>
		<description><![CDATA[It&#8217;s Wednesday and time for our first free weekly helping from the Think Vitamin Membership video library. Today Jim looks at getting started with the popular programming language PHP. In this 8 minute video he shows you how to install PHP and write your first lines of PHP code.]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s Wednesday and time for our first free weekly helping from the <a href="http://membership.thinkvitamin.com/">Think Vitamin Membership</a> video library. </p>
<p>Today Jim looks at getting started with the popular programming language PHP. In this 8 minute video he shows you how to install PHP and write your first lines of PHP code.</p>
<p><!-- Start of Brightcove Player --></p>
<div style="display:none">
</div>
<p><!--<br />
By use of this code snippet, I agree to the Brightcove Publisher T and C<br />
found at https://accounts.brightcove.com/en/terms-and-conditions/.<br />
--></p>
<p><script language="JavaScript" type="text/javascript" src="http://admin.brightcove.com/js/BrightcoveExperiences.js"></script></p>
<p><object id="myExperience180458571001" class="BrightcoveExperience"><param name="bgcolor" value="#FFFFFF" /><param name="width" value="705" /><param name="height" value="388" /><param name="playerID" value="89176682001" /><param name="playerKey" value="AQ%2E%2E,AAAAFEediwk%2E,2euW9ZlTxZAx4lLOZ1DtKcbmqEvxwq5q" /><param name="isVid" value="true" /><param name="isUI" value="true" /><param name="dynamicStreaming" value="true" /><param name="@videoPlayer" value="180458571001" /></object></p>
<p><!--<br />
This script tag will cause the Brightcove Players defined above it to be created as soon<br />
as the line is read by the browser. If you wish to have the player instantiated only after<br />
the rest of the HTML is processed and the page load is complete, remove the line.<br />
--><br />
<script type="text/javascript">brightcove.createExperiences();</script></p>
<p><!-- End of Brightcove Player --></p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/php-basics-installation-video-tutorial/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Exception Handling in PHP5</title>
		<link>http://thinkvitamin.com/code/exception-handling-in-php5/</link>
		<comments>http://thinkvitamin.com/code/exception-handling-in-php5/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 12:00:30 +0000</pubDate>
		<dc:creator>Lorna Jane Mitchell</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=6654</guid>
		<description><![CDATA[This article follows on from my earlier posts, introducing OOP in PHP, taking a closer look at OOP concepts in PHP, and also covering the various magic methods on offer in PHP 5. We&#8217;ll now move on to look at exceptions, which is how PHP 5 handles errors in an object-oriented way. What are Exceptions? [...]]]></description>
			<content:encoded><![CDATA[<p>This article follows on from my earlier posts, <a href="http://thinkvitamin.com/dev/getting-started-with-oop-php5/">introducing OOP in PHP</a>, taking <a href="http://thinkvitamin.com/dev/getting-started-with-oop-php5-part-2/">a closer look at OOP concepts in PHP</a>, and also covering the various <a href="http://thinkvitamin.com/dev/9-magic-methods-for-php">magic methods</a> on offer in PHP 5.  We&#8217;ll now move on to look at exceptions, which is how PHP 5 handles errors in an object-oriented way.<br />
<span id="more-6654"></span></p>
<h3>What are Exceptions?</h3>
<p>Exceptions are the PHP 5 way of flagging up an unexpected event.  They contain an information message, and can be extended just like any other object.  Exceptions are thrown rather than warnings in newer PHP extensions, although you do still see extensions returning errors.</p>
<p>When an exception is thrown, we either catch it where it happens, or it causes the code to return to its calling context.  If it isn&#8217;t caught there, it returns again, and so on.  As usual it is easier to explain with examples than words! </p>
<p>Here is an example in which <tt>DateTimeZone</tt> objects are created, first with a valid timezone string of &#8216;Europe/Amsterdam&#8217;, then another with an invalid timezone &#8216;nonsense&#8217;:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$timezone</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTimeZone<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Europe/Amsterdam'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">var_dump</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$timezone</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$timezone2</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTimeZone<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'nonsense'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>As the <a href="http://www.php.net/manual/en/datetimezone.construct.php">documentation explains</a>, <tt>DateTimeZone</tt> throws an exception when called with unexpected data.  This indeed happens if you run the above script, and the exception appears as an error message from PHP, looking something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">Exception<span style="color: #339933;">:</span> DateTimeZone<span style="color: #339933;">::</span>__construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span> Unknown or bad timezone <span style="color: #009900;">&#40;</span>nonsense<span style="color: #009900;">&#41;</span> in <span style="color: #339933;">/...../</span>exception1<span style="color: #339933;">.</span>php on line <span style="color: #cc66cc;">6</span></pre></div></div>

<p>We don&#8217;t want our entire application to stop and spit out errors over a nonsense timezone, and working with exceptions means we can do so much more with these situations than we can with errors.  We &#8220;<tt>catch</tt>&#8221; exceptions and can use the information in the exception itself and in the context of the current scope to decide how best to react.</p>
<p>This is a great improvement on the previous situation of having a few different error levels and only being able to choose whether to display, log or ignore each level as was the situation before PHP 5.</p>
<h3>Handling Exceptions</h3>
<p>We handle exceptions with a try/catch block like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">try <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$timezone2</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTimeZone<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'nonsense'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;time!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch<span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Oops!  Something bad happened!&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The &#8220;<tt>try</tt>&#8221; bit goes around the code that you would normally write, but which contains operations which can cause an exception.  The &#8220;<tt>catch</tt>&#8221; bit states what kind of exception to catch, and contains the code to execute if we do catch anything.</p>
<p>If you ran this script with a valid timezone as the argument to the <tt>DateTimeZone</tt> constructor, you would see the &#8220;time!&#8221; output and never enter the code inside the &#8220;catch&#8221; block.  However in our example, an exception will be caused and so we jump straight into this block, without echoing &#8220;time!&#8221;.</p>
<p>This is a fairly key concept &#8211; the code in the try block actually stops and we jump into the catch block and start executing from there.  Any code after the point at which the exception is throw simply isn&#8217;t run.</p>
<h3>Inside an Exception</h3>
<p>Exceptions can hold all sorts of information.  If we inspect our Exception thrown by DateTimeZone&#8217;s constructor using <tt>print_r</tt>, we&#8217;d see something like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">Exception Object
<span style="color: #009900;">&#40;</span>
    <span style="color: #009900;">&#91;</span>message<span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">protected</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> DateTimeZone<span style="color: #339933;">::</span>__construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span> Unknown or bad timezone <span style="color: #009900;">&#40;</span>nonsense<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#91;</span>string<span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">private</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span>
    <span style="color: #009900;">&#91;</span>code<span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">protected</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">0</span>
    <span style="color: #009900;">&#91;</span><span style="color: #990000;">file</span><span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">protected</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #339933;">/</span>home<span style="color: #339933;">/</span>lorna<span style="color: #339933;">/</span>data<span style="color: #339933;">/</span>personal<span style="color: #339933;">/</span>publish<span style="color: #339933;">/</span>thinkvitamin<span style="color: #339933;">/</span>exceptions<span style="color: #339933;">/</span>exceptions2<span style="color: #339933;">.</span>php
    <span style="color: #009900;">&#91;</span>line<span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">protected</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">4</span>
    <span style="color: #009900;">&#91;</span>trace<span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">private</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">Array</span>
        <span style="color: #009900;">&#40;</span>
            <span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">Array</span>
                <span style="color: #009900;">&#40;</span>
                    <span style="color: #009900;">&#91;</span><span style="color: #990000;">file</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #339933;">/</span>home<span style="color: #339933;">/</span>lorna<span style="color: #339933;">/</span>data<span style="color: #339933;">/</span>personal<span style="color: #339933;">/</span>publish<span style="color: #339933;">/</span>thinkvitamin<span style="color: #339933;">/</span>exceptions<span style="color: #339933;">/</span>exceptions2<span style="color: #339933;">.</span>php
                    <span style="color: #009900;">&#91;</span>line<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">4</span>
                    <span style="color: #009900;">&#91;</span><span style="color: #000000; font-weight: bold;">function</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> __construct
                    <span style="color: #009900;">&#91;</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> DateTimeZone
                    <span style="color: #009900;">&#91;</span>type<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #339933;">-&gt;</span>
                    <span style="color: #009900;">&#91;</span>args<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">Array</span>
                        <span style="color: #009900;">&#40;</span>
                            <span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> nonsense
                        <span style="color: #009900;">&#41;</span>
&nbsp;
                <span style="color: #009900;">&#41;</span>
&nbsp;
        <span style="color: #009900;">&#41;</span>
&nbsp;
    <span style="color: #009900;">&#91;</span>severity<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">2</span>
<span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>Walking through the object, there are many useful elements here:</p>
<ul>
<li><b>message</b> This contains a useful and relevant information message</li>
<li><b>code</b> By default this is zero but we can use this to include a numeric error code with our exception</li>
<li><b>file</b> Path to the file where this exception was thrown</li>
<li><b>line</b> Line number where the exception was thrown</li>
<li><b>trace </b>This is the stack trace, so you can see the stack of calls which were made before this exception was thrown</li>
</ul>
<p>This is all valuable information and we can use it to inform how we handle errors in the catch block in our code.  In addition we&#8217;ll take a look at how we can set these ourselves by making our own exceptions a little later on.</p>
<h3>Throwing Exceptions</h3>
<p>It isn&#8217;t only PHP itself that can throw exceptions, we can use exactly the same functionality in our own code.  Here is a really simple example, taken directly from <a href="http://php.net/manual/en/language.exceptions.php">the PHP manual</a> itself, of how to throw an exception manually.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> inverse<span style="color: #009900;">&#40;</span><span style="color: #000088;">$x</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$x</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Division by zero.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">return</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">/</span><span style="color: #000088;">$x</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>We simply throw a new <tt>Exception</tt> object, that we create as we need it.  The string passed into the constructor becomes the object&#8217;s message property, and we can also pass a second argument to the constructor if we want to set the code property as well.</p>
<p>It is usual to throw exceptions in functions or methods, and then catch them from the location they are called &#8211; this lets the calling code decide what to do in the context of what it intended and is much more flexible than simple errors or having your methods return false and set an error string somewhere, which I&#8217;m sure is how I solved this before exceptions were introduced in PHP 5.</p>
<h3>Extending Exceptions</h3>
<p>The Exception object by itself is great, but we can extend it so that we can return additional information and different types of exceptions &#8211; so if one of a number of different scenarios actually happens, we can respond differently.  Consider this script and in particular the <tt>takeTwoNumbers</tt> function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> BigNumberException <span style="color: #000000; font-weight: bold;">extends</span> Exception <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">class</span> FavouriteNumberException <span style="color: #000000; font-weight: bold;">extends</span> Exception <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> takeTwoNumbers<span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #339933;">,</span> <span style="color: #000088;">$b</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">15</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$b</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">15</span> <span style="color: #339933;">||</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$b</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">20</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> BigNumberException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Keep it simple with smaller numbers'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">elseif</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span> <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">3</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000088;">$b</span> <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">3</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> FavouriteNumberException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'But three is my favourite number!'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$a</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$b</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
try <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> takeTwoNumbers<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">9</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> takeTwoNumbers<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">4</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">16</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> takeTwoNumbers<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">7</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch<span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$e</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The function accepts two numbers, checks the values, and if there are any problems, throws a relevant exception.  If the values are OK (and yes, this is a totally contrived example, in an effort to illustrate the concept without any complicating factors like the real world getting involved!) then the function simply adds them together and returns them.</p>
<p>Our calling script calls the function 3 times, with different number sets.  The first one executes fine and the numbers get added together.  However the second includes a large number and so an error is thrown, causing our code to jump to the &#8220;<tt>catch</tt>&#8221; block, and so the third function call is never made.</p>
<p>Although we declared empty classes to extend <tt>Exception</tt> here and so only the class name changed, you can do all sorts of things to help record the information you need.  We would set custom error messages here (remember the helpful error message returned by <tt>DateTimeZone</tt>?), set error codes, or even set new properties of our own.</p>
<p>It depends on your application which of these is helpful but having the custom exception classes makes it very nice and tidy to do so.  The differing class names let us detect what *kind* of a problem occured and what we want to do in response.  When we catch an exception, we can state what kind of an exception we wanted to catch &#8211; so we can narrow ourselves down to only dealing with a known situation.  We can also use multiple catch blocks, like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">try <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> takeTwoNumbers<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">9</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> takeTwoNumbers<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">4</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">16</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> takeTwoNumbers<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">7</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch<span style="color: #009900;">&#40;</span>BigNumberException <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Big Number: &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$e</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> catch<span style="color: #009900;">&#40;</span>FavouriteNumberException <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Favourite Number: &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$e</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In this example, we can handle the two types of exception differently.  If any other type of exception were to occur, it wouldn&#8217;t be caught here, but instead would &#8220;bubble&#8221; up the stack, getting returned from the end of the second catch block to wherever this code was called from &#8211; in this very simple example we are in a simple PHP file but if we were nested in functions, the code would keep on returning until PHP caught the exception, or until it reached the top at which point it would show an error like the one we saw at the start of this post.</p>
<h3>Uncaught Exceptions</h3>
<p>So if an exception is thrown in a method, and not caught, it returns from the function to where that function is called from.  If it isn&#8217;t caught here, it returns to where this code was called from, and so on until it reaches the top of the stack.  If it gets to the top of the stack, uncaught, we&#8217;ll see the error we saw at the beginning of the post. </p>
<p>We can also give PHP instructions about how to handle any exceptions that get this far, using <a href="http://www.php.net/manual/en/function.set-exception-handler.php"><tt>set_exception_handler</tt></a>.  Many frameworks will do this and return nicely formatted messages, often logging the detail of the error so that users do not see it but developers can do so.</p>
<p>Here&#8217;s an example of a catch-all exception handling function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> my_exception_handler<span style="color: #009900;">&#40;</span><span style="color: #000088;">$exception</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">error_log</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Uncaught &quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">get_class</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$exception</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; exception: &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$exception</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
set_exception_handler<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'my_exception_handler'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Oooops!'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>All we need to do is declare our exception handling function and then tell PHP to use it for uncaught exceptions.  This simple example simply passes a string to <a href="http://www.php.net/manual/en/function.error-log.php"><tt>error_log</tt></a> function, which you can configure to behave however you need it to for your system.  In a real-world application you might want to notify administrators of the problem or perhaps provide some nice feedback to the user in addition to logging the error.</p>
<h3>Exceptions in Your Applications</h3>
<p>Hopefully this has given some insight into what you can do with exceptions and how they interact with the rest of your object-oriented application.  Even functional code needs awareness of exceptions since some core language elements now throw them, so it is worth making sure you have the exception handler declared alongside your existing error handler even if you don&#8217;t need to be extending or throwing exceptions yourself.  </p>
<p>Are you extending the Exception class?  What do you use this for?  I&#8217;m really interested to hear about the various applications of this theory so let me know in the comments!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/exception-handling-in-php5/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Getting Started with WordPress Custom Menus</title>
		<link>http://thinkvitamin.com/code/getting-started-with-wordpress-custom-menus/</link>
		<comments>http://thinkvitamin.com/code/getting-started-with-wordpress-custom-menus/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 11:00:39 +0000</pubDate>
		<dc:creator>Richard Shepherd</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=6437</guid>
		<description><![CDATA[Perhaps one of the biggest holes in WordPress prior to version 3 was the lack of custom menu support. Menus often had to be hand coded into header.php and, whilst they could be &#8216;smart&#8217;, it often let the client needing a PHP savvy developer to make alterations to the setup. That was then. Now, at [...]]]></description>
			<content:encoded><![CDATA[<p>Perhaps one of the biggest holes in WordPress prior to version 3 was the lack of custom menu support. Menus often had to be hand coded into <tt>header.php</tt> and, whilst they could be &#8216;smart&#8217;, it often let the client needing a PHP savvy developer to make alterations to the setup.</p>
<p>That was then. Now, at (long) last, we are able to give some of this control back to the client. Or, if you&#8217;re using WordPress for your own site, you&#8217;re able to take control of your menu system with a wonderful new drag-and-drop GUI rather than diving into the code.<span id="more-6437"></span></p>
<h3>New Menu System</h3>
<p>The menu system is based on <a href="http://www.woothemes.com/2010/01/the-awesome-custom-woo-navigation/">WooNavigation</a>, a custom menu system used by the ubiquitous <a href="http://www.woothemes.com/">WooThemes</a> in the latest versions of their custom framework. Although much of the code was rewritten for WordPress 3, the similarities are still clear.</p>
<p>Adii Pienaar from WooThemes recently told me:</p>
<blockquote><p>&#8220;The new menu system that WooThemes contributed is firstly long overdue and is a massive benefit to every single WordPress user. In essence, this is such a basic feature of any CMS, but due to it being a benefit to all WP users, I think this is a significant new addition.&#8221;</p></blockquote>
<p>Chris Coyier from CSS Tricks agrees:</p>
<blockquote><p>&#8220;Personally I think this is a big step forward because, together with Custom Post Types, it is migrating WordPress towards a fully fledged CMS. The more power we can give the end user, the easier it is for developers and designers with an understanding of PHP to use WordPress as a content management solution.&#8221;</p></blockquote>
<p>So, without further ado, let&#8217;s take a look at how it all works. Grab yourself a WordPress 3 install with a bunch of pages and a refreshing beverage. It&#8217;s thirsty work.</p>
<h3>Activating a Custom Menu</h3>
<p>If you&#8217;re using WordPress 3 with the (brand new) default Theme TwentyTen installed this next bit won&#8217;t apply, because it&#8217;s already set up to use custom menus, so let&#8217;s assume you&#8217;re working with an older theme or perhaps even building your own. When you log into WordPress, go to <tt>Appearance &gt; Menus</tt>.</p>
<p>If your current theme doesn&#8217;t support custom menus you&#8217;ll see this error message:</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Picture-1.png" alt="" width="297" height="132" /></p>
<p>This means we need to head over to <tt>functions.php</tt> and get our hands a little dirty with some code. Open up <tt>functions.php</tt> and add in the following code:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">add_action<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'init'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'register_custom_menu'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> register_custom_menu<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
register_nav_menu<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'custom_menu'</span><span style="color: #339933;">,</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Custom Menu'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><tt>register_nav_menu</tt> has two parameters here, the first is the slug we&#8217;ll use in our code and the second is the name our menu will have in the WordPress admin area.</p>
<p>Now before we head back over to the menu screen, let&#8217;s stay in the source code and tell WordPress wear to put this menu. The most likely place will be in <tt>header.php</tt>, but of course there is no reason you can&#8217;t put a menu anywhere on your page. To keep things simple for our first menu let&#8217;s open <tt>header.php</tt> and, at whatever point makes sense in your theme, add the following line:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> wp_nav_menu<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'menu'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'custom_menu'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>With just the default &#8216;About&#8217; page in our theme, if we look at our site we&#8217;ll see the following in the source code:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>div<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>ul<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>li<span style="color: #339933;">&gt;&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;the-link-in-here&quot;</span> title<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;About&quot;</span><span style="color: #339933;">&gt;</span>About<span style="color: #339933;">&lt;/</span>a<span style="color: #339933;">&gt;&lt;/</span>li<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>ul<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>div<span style="color: #339933;">&gt;</span></pre></div></div>

<p>And that&#8217;s all there is to it! Of course, we can add in a bunch of options into that array. You can check out the details over at the <a href="http://codex.wordpress.org/Function_Reference/wp_nav_menu">WordPress codex</a> and here are a few of the more important ones explained:</p>
<ul>
<li><tt>menu</tt> &#8211; which menu to call. In our example we only have one but you can set up as many menus as you like</li>
<li><tt>container</tt> &#8211; what element is wrapped around the menu. The default is a standard <tt>&lt;div&gt;</tt> but if you&#8217;re playing with the new kids over at HTML5 you could always change this to <tt>&lt;nav&gt;</tt></li>
<li><tt>container_class</tt> &#8211; the css class given to this container, helpful for custom styling</li>
<li><tt>menu_class</tt> &#8211; the css class given to the <tt>&lt;ul&gt;</tt> that is rendered. The default is &#8216;menu&#8217;, and again this is helpful for custom styling.</li>
<li><tt>depth</tt> &#8211; How many levels should the menu display. The default is 0&#8242; which means all levels, but you can set this to perhaps 1&#8242; or 2&#8242; to limit how far a drop-down menu will render. Handy stuff!</li>
</ul>
<p>That&#8217;s probably enough for our purposes, but it&#8217;s definitely worth checking out the WordPress codex because there are many options you can set, like adding text before and after menu items and links.</p>
<h3>Using the GUI</h3>
<p>So let&#8217;s get cracking with the user interface, where much of the magic happens.</p>
<p>The first thing we need to do is create our first menu (remember, we can have multiple menus) so I&#8217;ll imaginatively create one called &#8216;Our First Menu&#8217;. Type that in to the Menu Name field and hit the Create Menu Button.</p>
<p>Did you spot the check-box &#8216;Automatically add new top-level pages&#8217;? Well, do you?</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-13.png" alt="" width="470" /></p>
<p>Normally I don&#8217;t, because I figure if we&#8217;re going to the trouble of making a custom menu we probably don&#8217;t want it doing anything automatically. After all, we want complete control over our menu, so I don&#8217;t want WordPress dropping in a new page every time we create one. Maybe you do, and that&#8217;s okay with me too :)</p>
<p>Excellent! Our first menu is empty but we&#8217;re well on our way. Over on the left we&#8217;re told that our theme currently only supports one menu so we best make sure we&#8217;re using &#8216;Our First Menu&#8217;. Select it in the drop-down, and click Save.</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-11.png" alt="" width="291" height="188" /></p>
<h3>Adding Pages to our Menu</h3>
<p>So we&#8217;ve created a place in our theme for the menu, and now we&#8217;ve created the menu itself. Trouble is, there&#8217;s probably nothing in it. WordPress gives us three easy ways to add content to the menu, and the great news is that it doesn&#8217;t have to be content that sits in the WordPress site. For example, the first box on the left you&#8217;ll see is for Custom Links.</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-9.png" alt="" width="290" height="159" /></p>
<p>You could perhaps link to your twitter account like I have in the screen-shot above, and just click &#8216;Add to Menu&#8217;. It might be your portfolio, which you&#8217;ve hosted elsewhere, or links to live client sites. It might even be links to your favourite news sites. Whatever you choose, it&#8217;s great to know your menu can take your visitors anywhere.</p>
<p>The second (and probably most often used) way to add content to the menu is in the Pages&#8217; box, under &#8216;Custom Links&#8217;.</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-8.png" alt="" width="293" height="171" /></p>
<p>As you can see, I&#8217;m working on a fresh install of WordPress 3 which gives me just two pages &#8211; Home, and About. Now &#8216;Home&#8217; strictly speaking isn&#8217;t a page in the default configuration (although you can change that). For me, &#8216;Home&#8217; is whatever resides at and in <tt>index.php</tt>. </p>
<p>Notice the tabs at the top of the &#8216;Pages&#8217; box, which allow you to hunt around through content rich sites for exactly the pages you want. If you&#8217;re setting up your menu for the first time you might want to look in the &#8216;View All&#8217; tab, or if you&#8217;re just adding in a page you might want to &#8216;Search&#8217; for it.</p>
<p>I&#8217;m going to select both Home and About so I&#8217;ve got something to play with. If I hit &#8216;Add to Menu&#8217; you can see that my menu is really starting to shape up.</p>
<p>Finally we have the &#8216;Categories&#8217; box, which acts in much the same way as the &#8216;Tabs&#8217; box. Again, as this is the default install of WordPress I only have one category, the much maligned &#8216;Uncategorized&#8217;.</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-6.png" alt="" width="288" height="147" /></p>
<p>I&#8217;m going to select it (most of my posts often accidentally end up in uncategorized!) and &#8216;Add to Menu&#8217;. This is what we now have:</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-4.png" alt="" width="479" height="366" /></p>
<p>Now before we move on you need to &#8216;Save Menu&#8217;, so go ahead and click it.</p>
<p>To prove that this has worked we can load up my simple blog (which has the TwentyTen theme installed) and marvel at it&#8217;s glory.</p>
<p><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-3.png" alt="" width="445" height="430" /></p>
<h3>Menu Hierarchy</h3>
<p>That&#8217;s cool but it&#8217;s also only the beginning. The next thing to look at is ordering your menu hierarchy. So far the menu items have just appeared in the order we added them, but we probably want to change this. The good news is that this the whole system is drag-and-drop, so go ahead and move things around. </p>
<p>What you&#8217;ll also notice is that you can create a hierarchy by dragging items onto other items. I&#8217;ve added a few more pages and created something that looks like this:</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/menu-with-hierarchy.png" alt="" width="414" height="486" /></p>
<p>You can see I&#8217;ve created a hierarchy of pages as indicated by their indents, and I&#8217;ve also changed the name of &#8216;uncategorized&#8217; to &#8216;The Blog&#8217;. If we whizz on over to the actual site, we can also see that WordPress has created a funky drop down menu for me.</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/menu-with-hierarchy-live.png" alt="" width="426" height="329" /></p>
<p>Now it&#8217;s worth noting that TwentyTen is designed to style the menu as a drop-down, and that the actual HTML WordPress generates looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;div&gt;
&lt;ul id=&quot;menu-our-first-menu&quot;&gt;&lt;li id=&quot;menu-item-5&quot;&gt;&lt;a title=&quot;The home page&quot; href=&quot;http://localhost/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
&lt;li id=&quot;menu-item-6&quot;&gt;&lt;a href=&quot;http://localhost/?page_id=2&quot;&gt;About&lt;/a&gt;
&lt;ul&gt;
&lt;li id=&quot;menu-item-23&quot;&gt;&lt;a href=&quot;http://localhost/?page_id=9&quot;&gt;Our Company&lt;/a&gt;
&lt;ul&gt;
&lt;li id=&quot;menu-item-21&quot;&gt;&lt;a href=&quot;http://localhost/?page_id=13&quot;&gt;The Team&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li id=&quot;menu-item-22&quot;&gt;&lt;a href=&quot;http://localhost/?page_id=11&quot;&gt;Our Products&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li id=&quot;menu-item-20&quot;&gt;&lt;a href=&quot;http://localhost/?page_id=15&quot;&gt;Get in Touch&lt;/a&gt;
&lt;ul&gt;
&lt;li id=&quot;menu-item-19&quot;&gt;&lt;a href=&quot;http://localhost/?page_id=17&quot;&gt;Office Locations&lt;/a&gt;&lt;/li&gt;
&lt;li id=&quot;menu-item-4&quot;&gt;&lt;a href=&quot;http://twitter.com/richardshepherd&quot;&gt;My Twitter Stream&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li id=&quot;menu-item-8&quot;&gt;&lt;a href=&quot;http://localhost/?cat=1&quot;&gt;The Blog&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;</pre></div></div>

<h3>A Few More Options</h3>
<p>You should also be able to see in the Menus admin that each menu has a drop-down arrow. Click on it, and you&#8217;ll see there are a few things you can tinker with.</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-19.png" alt="" width="417" height="197" /></p>
<ul>
<li><tt>URL </tt>- The url which the menu item links to</li>
<li><tt>Navigation Label </tt>- What it will actually say in the menu</li>
<li><tt>Title Attribute </tt>- Useful for making your menu accessible, and you could also use some jQuery to grab this and create a piece of &#8216;description&#8217; text</li>
<li><tt>Remove/Cancel </tt>- No prizes here</li>
</ul>
<h3>Menu Widgets</h3>
<p>There&#8217;s one more thing we&#8217;ll look at in this introductory tutorial, and that&#8217;s the menu widget. So far all we&#8217;ve done is actually create a menu in our header and stick &#8216;Our First Menu&#8217; into that hook. There is one other thing Custom Menu&#8217;s do out-of-the-box. In the WordPress admin head on over to <tt>Appearance &gt; Widgets</tt> and we can take a look at the Custom Menu Widget.</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-18.png" alt="" width="255" height="72" /></p>
<p>It should be sitting under Available Widgets, so drag it over to one of your widgetized areas and let&#8217;s take a look at the options:</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-17.png" alt="" width="292" height="265" /></p>
<p>As you can see, there aren&#8217;t many! You can give the widget a title (I&#8217;ve called mine &#8216;Our Menu Widget&#8217;) and then select which menu you have created to use. Now we only created one menu in this tutorial, but you could of course create a second and drop it in here. Click &#8216;Save&#8217;, head on over to your site and you should see something like this:</p>
<p style="text-align: center;"><img src="http://carsonified.com/wp-content/uploads/2010/07/Google-Chrome-16.png" alt="" width="367" height="311" /></p>
<p>And that&#8217;s it! Great for a sitemap-like feature, just remember that if your menu doesn&#8217;t automatically update when you add new pages neither will this widget.</p>
<h3>Just the Beginning</h3>
<p>As you can probably tell, there&#8217;s a lot going on with the Custom Menu feature. I&#8217;ve tried to stick to the basics here and focus on the GUI, but there is a lot more going on under the hood that is also worth looking into. If you feel confident with PHP then start playing &#8211; there&#8217;s so much more you can do.</p>
<p>If all you are looking for is a simple way to create and manage menus for you and your clients, we hope this overview gets you started. As always, we welcome your comments and look forward to seeing Custom Menus on your WordPress sites!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/getting-started-with-wordpress-custom-menus/feed/</wfw:commentRss>
		<slash:comments>55</slash:comments>
		</item>
		<item>
		<title>Create your first WordPress Custom Post Type</title>
		<link>http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/</link>
		<comments>http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 10:00:02 +0000</pubDate>
		<dc:creator>Richard Shepherd</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=6257</guid>
		<description><![CDATA[Let me get something off my chest. WordPress sometimes, just ever-so occasionally, makes things sound a little harder than they actually are. Custom post types sound quite scary, but really they aren&#8217;t. Jane Wells, WordPress UI guru, commented on their name in my last article for Think Vitamin: &#8220;They just got named poorly because they [...]]]></description>
			<content:encoded><![CDATA[<p>Let me get something off my chest. WordPress sometimes, just ever-so occasionally, makes things sound a little harder than they actually are. Custom post types sound quite scary, but really they aren&#8217;t. <a href="http://jane.wordpress.com/">Jane Wells</a>, WordPress UI guru, commented on their name in <a href="http://carsonified.com/blog/design/wordpress-3-0-for-web-designers/">my last article for Think Vitamin</a>:</p>
<blockquote><p>&#8220;They just got named poorly because they live in the Posts table in the database. Think of them more like custom objects/content types.&#8221;</p></blockquote>
<p>Cool &#8211; it&#8217;s just custom content. What&#8217;s the point of that then? Can&#8217;t we just categorise blog posts and order our pages in nice hierarchies? Can&#8217;t we use conditionals to spit out different CSS stylesheets? Well yes, we <em>could</em>. But admit it – it&#8217;s not fun.</p>
<p>And hands up if you&#8217;ve ever tried to explain to a client what a custom field is. Hurts, doesn&#8217;t it? So thank goodness for wonderful people like Jane who have given us a solution.<span id="more-6257"></span></p>
<h3>What is it and What it isn&#8217;t</h3>
<p>Everyone&#8217;s talking about them. I recently asked Chris Coyier from <a href="http://css-tricks.com/">CSS-Tricks</a> what excited him about WP3 and he replied custom post types:</p>
<blockquote><p>&#8220;Think of how <a href="http://tumblr.com/">Tumblr</a> works – how you can publish photos, quotes, links and whatever else. You could create those same types now with WordPress, and build themes to support and have special styles for them. This is fantastic stuff for building custom sites!&#8221;</p></blockquote>
<p>Make sense? Well according to Jane, Chris misinterpreted their goal:</p>
<blockquote><p>&#8220;Custom post types aren&#8217;t really meant for that use […] Custom post types are great for things that are more or less catalogued: products (in an e-commerce site), listings for a real estate site, etc. For regular content creation as described [by Chris], you can already do [that] by using custom taxonomies and/or stylesheets to make post templates.&#8221;</p></blockquote>
<p>Now I&#8217;m going to go out on a limb here and say that Chris made a interesting suggestion. I say this for two reasons: firstly because I think the great thing about WordPress is we can use it in the way we feel it <em>should</em> be used. There might be a different or better way, but there is no <em>wrong </em>way to do something (unless it doesn&#8217;t work!). Secondly I refuse to believe that many designers would read up on something as scarily titled as ‘<a href="http://codex.wordpress.org/WordPress_Taxonomy">custom taxonomies</a>&#8216;.</p>
<p>Indeed I expect to see WordPress themes cropping up all over the place that mimic the way Tumblr themes look and work. <a href="http://www.woothemes.com/">WooThemes</a> have already released three.</p>
<h3>Get your Hands Dirty</h3>
<p>Now before we dig in I want to say this – custom post types make things a lot easy for non-technical people to use the WordPress admin to enter content. However the designer/developer still needs to have a reasonable grasp of PHP and needs to be prepared to get their hands dirty (unless they opt for a plugin that does the job for you like <a href="http://wordpress.org/extend/plugins/custom-post-template/">http://wordpress.org/extend/plugins/custom-post-template/</a> or <a href="http://wordpress.org/extend/plugins/custom-post-type-ui/">http://wordpress.org/extend/plugins/custom-post-type-ui/</a>)</p>
<p>For our tutorial we&#8217;re going to be editing <tt>functions.php </tt>which is your theme directory. We&#8217;re simply adding to this file, so feel free to start at the top or at the bottom – just don&#8217;t change any of the code that&#8217;s already there. For the more confident of you out there you could adapt this code into a plugin.</p>
<p>With a few edits we are going to create a custom post type for our portfolio, and a template which will use this information. We&#8217;ll end up with a new panel in the admin menu which looks like this:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-AdminPanel.jpg"><img style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-AdminPanel.jpg" alt="A custom post type admin panel" /></a></p>
<p>A new overview page called &#8220;My Portfolio&#8221;:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Columns.jpg"><img style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Columns.jpg" alt="Custom Post Type admin page" width="470" /></a></p>
<p>And a new place to enter our content:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Edit.jpg"><img style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Edit.jpg" alt="Custom post type edit screen" width="470" /></a></p>
<h3>Step 1</h3>
<p>Here&#8217;s the first bit of code we need to add to <tt>functions.php</tt>, which I&#8217;ll review below.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">add_action<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'init'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'portfolio_register'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> portfolio_register<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000088;">$labels</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
		<span style="color: #0000ff;">'name'</span> <span style="color: #339933;">=&gt;</span> _x<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'My Portfolio'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'post type general name'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'singular_name'</span> <span style="color: #339933;">=&gt;</span> _x<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Portfolio Item'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'post type singular name'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'add_new'</span> <span style="color: #339933;">=&gt;</span> _x<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Add New'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'portfolio item'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'add_new_item'</span> <span style="color: #339933;">=&gt;</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Add New Portfolio Item'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'edit_item'</span> <span style="color: #339933;">=&gt;</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Edit Portfolio Item'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'new_item'</span> <span style="color: #339933;">=&gt;</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'New Portfolio Item'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'view_item'</span> <span style="color: #339933;">=&gt;</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'View Portfolio Item'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'search_items'</span> <span style="color: #339933;">=&gt;</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Search Portfolio'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'not_found'</span> <span style="color: #339933;">=&gt;</span>  __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Nothing found'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'not_found_in_trash'</span> <span style="color: #339933;">=&gt;</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Nothing found in Trash'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'parent_item_colon'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">''</span>
	<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$args</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
		<span style="color: #0000ff;">'labels'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$labels</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'public'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'publicly_queryable'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'show_ui'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'query_var'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'menu_icon'</span> <span style="color: #339933;">=&gt;</span> get_stylesheet_directory_uri<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/article16.png'</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'rewrite'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'capability_type'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'post'</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'hierarchical'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'menu_position'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">,</span>
		<span style="color: #0000ff;">'supports'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'title'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'editor'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'thumbnail'</span><span style="color: #009900;">&#41;</span>
	  <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
	register_post_type<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'portfolio'</span> <span style="color: #339933;">,</span> <span style="color: #000088;">$args</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Anyone who&#8217;s worked with WordPress before will recognise the structure here. We&#8217;re adding an action when the WP Admin initialises to call the function <tt>portfolio_register()</tt>. In that function we create two arrays, <tt>$labels</tt> and <tt>$args</tt>, and then use <tt><a href="http://codex.wordpress.org/Function_Reference/register_post_type">register_post_type</a></tt> to pull it all together. In doing so we name the new custom post type ‘portfolio&#8217; and tell it to use the arguments from <tt>$args</tt>.</p>
<p>The devil is in the detail, so let&#8217;s run over some of those arguments. A full list can be found at <a href="http://codex.wordpress.org/Function_Reference/register_post_type">http://codex.wordpress.org/Function_Reference/register_post_type</a>. First let&#8217;s look at <tt>$labels</tt>:</p>
<ul>
<li><strong>name </strong>– <em>this is the (probably plural) name for our new post type</em></li>
<li><strong>singular_name </strong>– <em>how you&#8217;d refer to this in the singular  (such as ‘Add new ****&#8217;) </em></li>
</ul>
<p>You can probably work out the rest of <em>$labels</em> for yourself, as they simply refer to different circumstances in which the name of your custom post type would be used.</p>
<p>And now <tt>$args</tt>:</p>
<ul>
<li><strong>public </strong>– <em>should they be shown in the admin UI </em></li>
<li><strong>show_ui </strong>– <em>should we display an admin panel for this custom post type </em></li>
<li><strong>menu_icon </strong>– <em>a custom icon for the admin panel</em></li>
<li><strong>capability_type </strong>- <em>WordPress will treat this as a ‘post&#8217; for read, edit, and delete capabilities </em></li>
<li><strong>hierarchical </strong>– <em>is it hierarchical, like pages </em></li>
<li><strong>rewrite </strong>– <em>rewrites permalinks using the slug ‘portfolio&#8217;</em></li>
<li><strong>supports </strong>– <em>which items do we want to display on the add/edit post page</em></li>
</ul>
<p>That&#8217;s the first simple step, and it should be enough to see your new custom post time in the WordPress admin. Save <tt>functions.php</tt> and take a look!</p>
<h3>Step 2</h3>
<p>The next thing we need to do is <a href="http://codex.wordpress.org/Function_Reference/register_taxonomy">register a taxonomy</a>. Or, in English, create categories for this new content type.</p>
<p>For example, in our portfolio we want to include the names of technologies and software used to create our work. I&#8217;m going to call this taxonomy ‘Skills&#8217;, and populate it with things like HTML, CSS and jQuery.</p>
<p>It&#8217;s just one line of code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">register_taxonomy<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Skills&quot;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;portfolio&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;hierarchical&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;label&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Skills&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;singular_label&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Skill&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;rewrite&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The first item here is the taxonomy name, ‘Skills&#8217;. The second is the name of the object type we&#8217;re applying it to, in our case the custom post type ‘portfolio&#8217; (which is an array). Finally our arguments; you can find a full list at <a href="http://codex.wordpress.org/Function_Reference/register_taxonomy">http://codex.wordpress.org/Function_Reference/register_taxonomy</a>, and here we&#8217;re using just three which have the same meaning as described in Step 1.</p>
<p>Add that line of code in and you should now see:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-AdminPanel.jpg"><img style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-AdminPanel.jpg" alt="A custom post type admin panel" /></a></p>
<p>You can then enter new ‘skills&#8217; just like you&#8217;d enter categories for blog posts. It looks like this:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Skills.jpg"><img style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Skills.jpg" alt="Custom post types - add skills" width="470" /></a></p>
<h3>Step 3</h3>
<p>The third step is to add custom data fields to the add/edit post page.</p>
<p>For our portfolio we can add things like the year the piece was published and details on who designed, built and produced the site/design.</p>
<p>There&#8217;s a bit more code here, but read through it in order and it should make sense:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">add_action(&quot;admin_init&quot;, &quot;admin_init&quot;);
&nbsp;
function admin_init(){
  add_meta_box(&quot;year_completed-meta&quot;, &quot;Year Completed&quot;, &quot;year_completed&quot;, &quot;portfolio&quot;, &quot;side&quot;, &quot;low&quot;);
  add_meta_box(&quot;credits_meta&quot;, &quot;Design &amp; Build Credits&quot;, &quot;credits_meta&quot;, &quot;portfolio&quot;, &quot;normal&quot;, &quot;low&quot;);
}
&nbsp;
function year_completed(){
  global $post;
  $custom = get_post_custom($post-&gt;ID);
  $year_completed = $custom[&quot;year_completed&quot;][0];
  ?&gt;
  &lt;label&gt;Year:&lt;/label&gt;
  &lt;input name=&quot;year_completed&quot; value=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$year_completed</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot; /&gt;
  <span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> credits_meta<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$post</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$custom</span> <span style="color: #339933;">=</span> get_post_custom<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$designers</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$custom</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;designers&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$developers</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$custom</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;developers&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$producers</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$custom</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;producers&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">?&gt;</span>
  &lt;p&gt;&lt;label&gt;Designed By:&lt;/label&gt;&lt;br /&gt;
  &lt;textarea cols=&quot;50&quot; rows=&quot;5&quot; name=&quot;designers&quot;&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$designers</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/textarea&gt;&lt;/p&gt;
  &lt;p&gt;&lt;label&gt;Built By:&lt;/label&gt;&lt;br /&gt;
  &lt;textarea cols=&quot;50&quot; rows=&quot;5&quot; name=&quot;developers&quot;&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$developers</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/textarea&gt;&lt;/p&gt;
  &lt;p&gt;&lt;label&gt;Produced By:&lt;/label&gt;&lt;br /&gt;
  &lt;textarea cols=&quot;50&quot; rows=&quot;5&quot; name=&quot;producers&quot;&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$producers</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/textarea&gt;&lt;/p&gt;
  <span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>First of all we call the add the admin_init function to the queue when the WordPress admin initialises, and within that function we <a href="http://codex.wordpress.org/Function_Reference/add_meta_box">add two meta boxes</a> – places to enter our data. The context for these two statements is</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> add_meta_box<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$id</span><span style="color: #339933;">,</span> <span style="color: #000088;">$title</span><span style="color: #339933;">,</span> <span style="color: #000088;">$callback</span><span style="color: #339933;">,</span> <span style="color: #000088;">$page</span><span style="color: #339933;">,</span> <span style="color: #000088;">$context</span><span style="color: #339933;">,</span> <span style="color: #000088;">$priority</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>The only difference between the two is where we place them on the screen. The ‘year completed&#8217; is placed in the sidebar using ‘side&#8217; whilst the ‘credits&#8217; are placed in the main flow of the page using ‘normal&#8217;.</p>
<p>Within the two functions there is some vanilla WordPress PHP code and HTML to help define our old friend custom fields. Make sure to include</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$post</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>…so that we can then query the current post using</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$custom</span> <span style="color: #339933;">=</span> get_post_custom<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Once the two new meta boxes have been added it looks like this:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Add.jpg"><img style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Add.jpg" alt="Custom post types - add new post" width="470" /></a></p>
<p>The final thing to do in step 3 is to make sure we then save these values with this post. I do this with</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">add_action<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'save_post'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'save_details'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>and</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> save_details<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$post</span><span style="color: #339933;">;</span>
&nbsp;
  update_post_meta<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;year_completed&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;year_completed&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  update_post_meta<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;designers&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;designers&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  update_post_meta<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;developers&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;developers&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  update_post_meta<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;producers&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;producers&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>There&#8217;s nothing too tricky here. Again we&#8217;re adding an action, this time to the ‘save_post&#8217; event. It fires the function <tt>save_details()</tt> which uses update_post_meta (<a href="http://codex.wordpress.org/Function_Reference/update_post_meta">http://codex.wordpress.org/Function_Reference/update_post_meta</a>) to save the relevant data.</p>
<h3>Step 4</h3>
<p>A nice little touch is to rejig the layout of the My Portfolio page to display some of this information. If you&#8217;ve followed through the article so far this should all make sense to you:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">add_action<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;manage_posts_custom_column&quot;</span><span style="color: #339933;">,</span>  <span style="color: #0000ff;">&quot;portfolio_custom_columns&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
add_filter<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;manage_edit-portfolio_columns&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;portfolio_edit_columns&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> portfolio_edit_columns<span style="color: #009900;">&#40;</span><span style="color: #000088;">$columns</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$columns</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">&quot;cb&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;&lt;input type=<span style="color: #000099; font-weight: bold;">\&quot;</span>checkbox<span style="color: #000099; font-weight: bold;">\&quot;</span> /&gt;&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;title&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Portfolio Title&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;description&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Description&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;year&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Year Completed&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;skills&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Skills&quot;</span><span style="color: #339933;">,</span>
  <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">return</span> <span style="color: #000088;">$columns</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> portfolio_custom_columns<span style="color: #009900;">&#40;</span><span style="color: #000088;">$column</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$post</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$column</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;description&quot;</span><span style="color: #339933;">:</span>
      the_excerpt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;year&quot;</span><span style="color: #339933;">:</span>
      <span style="color: #000088;">$custom</span> <span style="color: #339933;">=</span> get_post_custom<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$custom</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;year_completed&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;skills&quot;</span><span style="color: #339933;">:</span>
      <span style="color: #b1b100;">echo</span> get_the_term_list<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Skills'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">', '</span><span style="color: #339933;">,</span><span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here we&#8217;re adding two more functions to the WordPress Admin. The first, <tt>portfolio_edit_columns($columns)</tt>, simply defines the columns. The first two arguments &#8220;cb&#8221; and &#8220;title&#8221; are part of the core so don&#8217;t play with those too much (you can of course rename &#8220;Portfolio Title&#8221;). It&#8217;s the next three that come from our custom post type, &#8220;description&#8221;, &#8220;year&#8221; and &#8220;skills&#8221;.</p>
<p>We have one more function to tell WordPress where to get this data from &#8211; <tt>portfolio_custom_columns($column)</tt>. Using a simple switch/case we can define what data to actually show in the column layout. For the &#8220;description&#8221; we use <a href="http://codex.wordpress.org/Template_Tags/the_excerpt" target="_blank"><tt>the_excerpt()</tt></a>, for &#8220;year&#8221; we get the custom field data using <a href="http://codex.wordpress.org/Function_Reference/get_post_custom" target="_blank"><tt>get_post_custom()</tt></a>, and for &#8220;skills&#8221; we get a comma separated list of the terms/taxonomies/categories using <a href="http://codex.wordpress.org/Function_Reference/get_the_term_list" target="_blank"><tt>get_the_term_list()</tt></a>.</p>
<p>With that we have our customised columns:</p>
<p><a href="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Columns.jpg"><img style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/WP-CPT-Columns.jpg" alt="Custom Post Type admin page" width="470" /></a></p>
<h3>One final touch</h3>
<p>Be default custom post types will display using single.php, or index.php as a fallback. The great thing is we can create our own custom template using the filename <tt>single-xxxxxx.php</tt>. In our case this is single-portfolio.php. Just create your template file in your theme directory and the custom post type will use it. How you display the data is totally up to you.</p>
<p>Hey, did you also notice the &#8216;Featured Image&#8217; option on the add/edit page. That works out-of-the-box thanks to the  &#8216;thumbnail&#8217; part of:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #0000ff;">'supports'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'title'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'editor'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'thumbnail'</span><span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>You just need to make sure to include the following line of code in <tt>functions.php</tt>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">add_theme_support<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'post-thumbnails'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>For more details check out this <a href="http://markjaquith.wordpress.com/2009/12/23/new-in-wordpress-2-9-post-thumbnail-images/" target="_blank">excellent post by Mark Jaquith</a>.</p>
<h3>Rewrite Problems?</h3>
<p>There are a few reported problems out there about the rewriting of custom URLs; in short, they sometimes don&#8217;t work. However, if you&#8217;re experiencing this problem there are a couple of easy fixes.</p>
<p>First, simply go to the Settings &gt; Permalinks page, which will flush the permalinks (assuming that your WordPress install can write to the .htaccess file). This should clear up most problems related to permalinks, custom post type related or not.</p>
<p>If that doesn&#8217;t work you can add a line of code <em>after </em>you register the post type:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">	register_post_type<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'portfolio'</span> <span style="color: #339933;">,</span> <span style="color: #000088;">$args</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        flush_rewrite_rules<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>This worked for me on a particularly problematic install.</p>
<h3>Conclusion</h3>
<p>And there we have it! That is a whistle-stop tour of custom post  types which I hope gives you the appetite to explore further.</p>
<p>The best thing is to experiment with the code, read through the  documentation in the <a href="http://codex.wordpress.org/Main_Page" target="_blank">WordPress  Codex</a>, and share your ideas with others. Like any new feature I&#8217;m  sure it will evolve as users create new and exciting ways to use it, and  we&#8217;d love to hear about how you&#8217;re using custom post types here at  Think Vitamin.</p>
<div style="width: 1px;height: 1px;overflow: hidden">
<p>function portfolio_register() {</p>
<p>$labels = array(<br />
&#8216;name&#8217; =&gt; _x(&#8216;My Portfolio&#8217;, &#8216;post type general name&#8217;),<br />
&#8216;singular_name&#8217; =&gt; _x(&#8216;Portfolio Item&#8217;, &#8216;post type singular name&#8217;),<br />
&#8216;add_new&#8217; =&gt; _x(&#8216;Add New&#8217;, &#8216;portfolio item&#8217;),<br />
&#8216;add_new_item&#8217; =&gt; __(&#8216;Add New Portfolio Item&#8217;),<br />
&#8216;edit_item&#8217; =&gt; __(&#8216;Edit Portfolio Item&#8217;),<br />
&#8216;new_item&#8217; =&gt; __(&#8216;New Portfolio Item&#8217;),<br />
&#8216;view_item&#8217; =&gt; __(&#8216;View Portfolio Item&#8217;),<br />
&#8216;search_items&#8217; =&gt; __(&#8216;Search Portfolio&#8217;),<br />
&#8216;not_found&#8217; =&gt;  __(&#8216;Nothing found&#8217;),<br />
&#8216;not_found_in_trash&#8217; =&gt; __(&#8216;Nothing found in Trash&#8217;),<br />
&#8216;parent_item_colon&#8217; =&gt; &#8221;<br />
);</p>
<p>$args = array(<br />
&#8216;labels&#8217; =&gt; $labels,<br />
&#8216;public&#8217; =&gt; true,<br />
&#8216;publicly_queryable&#8217; =&gt; true,<br />
&#8216;show_ui&#8217; =&gt; true,<br />
&#8216;query_var&#8217; =&gt; true,<br />
&#8216;menu_icon&#8217; =&gt; get_stylesheet_directory_uri() . &#8216;/article16.png&#8217;,<br />
&#8216;_builtin&#8217; =&gt; false,<br />
&#8216;rewrite&#8217; =&gt; true,<br />
&#8216;capability_type&#8217; =&gt; &#8216;post&#8217;,<br />
&#8216;hierarchical&#8217; =&gt; false,<br />
&#8216;menu_position&#8217; =&gt; null,<br />
&#8216;supports&#8217; =&gt; array(&#8216;title&#8217;,'editor&#8217;,'thumbnail&#8217;)<br />
);</p>
<p>register_post_type( &#8216;portfolio&#8217; , $args );<br />
}</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/feed/</wfw:commentRss>
		<slash:comments>191</slash:comments>
		</item>
		<item>
		<title>9 Magic Methods for PHP</title>
		<link>http://thinkvitamin.com/code/9-magic-methods-for-php/</link>
		<comments>http://thinkvitamin.com/code/9-magic-methods-for-php/#comments</comments>
		<pubDate>Mon, 07 Jun 2010 08:00:48 +0000</pubDate>
		<dc:creator>Lorna Jane Mitchell</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=6000</guid>
		<description><![CDATA[Following on from my previous two posts, showing a gentle introduction to OOP in PHP and some slightly more advanced concepts, I&#8217;d like to take a dive into the magic methods in PHP. It might be magic, but no wands are required! The &#8220;magic&#8221; methods are ones with special names, starting with two underscores, which [...]]]></description>
			<content:encoded><![CDATA[<p>Following on from my previous two posts, showing a <a href="http://carsonified.com/blog/dev/getting-started-with-oop-php5/">gentle introduction to OOP in PHP </a>and some <a href="http://carsonified.com/blog/dev/getting-started-with-oop-php5-part-2/">slightly more advanced concepts</a>, I&#8217;d like to take a dive into the <a href="http://php.net/manual/en/language.oop5.magic.php">magic methods in PHP</a>. It might be magic, but no wands are required!</p>
<p>The &#8220;magic&#8221; methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events. </p>
<p>That might sound slightly automagical but actually it&#8217;s pretty straightforward, we already saw an example of this in the last post, where we used a constructor &#8211; so we&#8217;ll use this as our first example.</p>
<p><span id="more-6000"></span></p>
<h3>__construct</h3>
<p>The constructor is a magic method that gets called when the object is instantiated. It is usually the first thing in the class declaration but it does not need to be, it a method like any other and can be declared anywhere in the class. </p>
<p>Constructors also inherit like any other method. So if we consider our previous inheritance example from the Introduction to OOP, we could add a constructor to the Animal class like this:</p>
<pre><code>class Animal{

  public function __construct() {
    $this-&gt;created = time();
    $this-&gt;logfile_handle = fopen('/tmp/log.txt', 'w');
  }

}</code></pre>
<p><strong>animal.php</strong></p>
<p>Now we can create a class which inherits from the Animal class &#8211; a Penguin!  Without adding anything into the Penguin class, we can declare it and have it inherit from Animal, like this:</p>
<pre><code>class Penguin extends Animal {

}

$tux = new Penguin;
echo $tux-&gt;created;</code></pre>
<p>If we define a <tt>__construct</tt> method in the Penguin class, then Penguin objects will run that instead when they are instantiated. Since there isn&#8217;t one, PHP looks to the parent class definition for information and uses that. So we can override, or not, in our new class &#8211; very handy.</p>
<h3>__destruct</h3>
<p>Did you spot the file handle that was also part of the constructor?  We don&#8217;t really want to leave things like that lying around when we finish using an object and so the <tt>__destruct</tt> method does the opposite of the constructor. It gets run when the object is destroyed, either expressly by us or when we&#8217;re not using it any more and PHP cleans it up for us. For the Animal, our <tt>__destruct</tt> method might look something like this:</p>
<pre><code>class Animal{

  public function __construct() {
    $this-&gt;created = time();
    $this-&gt;logfile_handle = fopen('/tmp/log.txt', 'w');
  }

  public function __destruct() {
    fclose($this-&gt;logfile_handle);
  }
}</code></pre>
<p><strong>animal2.php</strong></p>
<p>The destructor lets us close up any external resources that were being used by the object. In PHP since we have such short running scripts (and look out for greatly improved garbage collection in newer versions), often issues such as memory leaks aren&#8217;t a problem. However it&#8217;s good practice to clean up and will give you a more efficient application overall!</p>
<h3>__get</h3>
<p>This next magic method is a very neat little trick to use &#8211; it makes properties which actually don&#8217;t exist appear as if they do. Let&#8217;s take our little penguin:</p>
<pre><code>class Penguin extends Animal {

  public function __construct($id) {
    $this-&gt;getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }
}</code></pre>
<p><strong>penguin1.php</strong></p>
<p>Now if our penguin has the properties &#8220;name&#8221; and &#8220;age&#8221; after it is loaded, we&#8217;d be able to do:</p>
<pre><code>$tux = new Penguin(3);
echo $tux-&gt;name . " is " . $tux-&gt;age . " years old\n";
</code></pre>
<p>However imagine something changed about the backend database or information provider, so instead of &#8220;name&#8221;, the property was called &#8220;username&#8221;. And imagine this is a complex application which refers to the &#8220;name&#8221; property in too many places for us to change. We can use the <tt>__get</tt> method to pretend that the &#8220;name&#8221; property still exists:</p>
<pre><code>class Penguin extends Animal {

  public function __construct($id) {
    $this-&gt;getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }

  public function __get($field) {
    if($field == 'name') {
      return $this-&gt;username;
    }
}</code></pre>
<p><strong>penguin2.php</strong></p>
<p>This technique isn&#8217;t really a good way to write whole systems, because it makes code hard to debug, but it is a very valuable tool. It can also be used to only load properties on demand or show calculated fields as properties, and a hundred other applications that I haven&#8217;t even thought of!</p>
<h3>__set</h3>
<p>So we updated all the calls to <tt>$this-&gt;name</tt> to return <tt>$this-&gt;username</tt> but what about when we want to set that value, perhaps we have an account screen where users can change their name?  Help is at hand in the form of the <tt>__set</tt> method, and easiest to illustrate with an example.</p>
<pre><code>class Penguin extends Animal {

  public function __construct($id) {
    $this-&gt;getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }

  public function __get($field) {
    if($field == 'name') {
      return $this-&gt;username;
    }
  }

  public function __set($field, $value) {
    if($field == 'name') {
      $this-&gt;username = $value;
    }
  }
}</code></pre>
<p><strong>penguin3.php</strong></p>
<p>In this way we can falsify properties of objects, for any one of a number of uses. As I said, not a way to build a whole system, but a very useful trick to know.</p>
<h3>__call</h3>
<p>There are actually two methods which are similar enough that they don&#8217;t get their own title in this post!  The first is the <tt>__call</tt> method, which gets called, if defined, when an undefined method is called on this object. </p>
<p>The second is <tt>__callStatic</tt> which behaves in exactly the same way but responds to undefined static method calls instead (only in new versions though, this was added in PHP 5.3). </p>
<p>Probably the most common thing I use <tt>__call</tt> for is polite error handling, and this is especially useful in library code where other people might need to be integrating with your methods. </p>
<p>So for example if a script had a Penguin object called <tt>$penguin</tt> and it contained <tt>$penguin-&gt;speak() ...</tt> the <tt>speak()</tt> method isn&#8217;t defined so under normal circumstances we&#8217;d see:</p>
<pre><code>PHP Fatal error:  Call to undefined method Penguin::speak() in ...</code></pre>
<p>What we can do is add something to cope more nicely with this kind of failure than the PHP fatal error you see here, by declaring a method <tt>__call</tt>. For example:</p>
<pre><code>class Animal {
}
class Penguin extends Animal {

  public function __construct($id) {
    $this-&gt;getPenguinFromDb($id);
  }

  public function getPenguinFromDb($id) {
    // elegant and robust database code goes here
  }

  public function __get($field) {
    if($field == 'name') {
      return $this-&gt;username;
    }
  }

  public function __set($field, $value) {
    if($field == 'name') {
      $this-&gt;username = $value;
    }
  }

  public function __call($method, $args) {
      echo "unknown method " . $method;
      return false;
  }
}</code></pre>
<p><strong>penguin4.php</strong></p>
<p>This will catch the error and echo it. In a practical application it might be more appropriate to log a message, redirect a user, or throw an exception, depending on what you are working on &#8211; but the concept is the same. </p>
<p>Any misdirected method calls can be handled here however you need to, you can detect the name of the method and respond differently accordingly &#8211; for example you could handle method renaming in a similar way to how we handled the property renaming above.</p>
<h3>__sleep</h3>
<p>The <tt>__sleep()</tt> method is called when the object is serialised, and allows you to control what gets serialised. There are all sorts of applications for this, a good example is if an object contains some kind of pointer, for example a file handle or a reference to another object. </p>
<p>When the object is serialised and then unserialised then these types of references are useless since the target may no longer be present or valid. Therefore it is better to unset these before you store them.</p>
<h3>__wakeup</h3>
<p>This is the opposite of the <tt>__sleep()</tt> method and allows you to alter the behaviour of the unserialisation of the object. Used in tandem with <tt>__sleep()</tt>, this can be used to reinstate handles and object references which were removed when the object was serialised. </p>
<p>A good example application could be a database handle which gets unset when the item is serialised, and then reinstated by referring to the current configuration settings when the item is unserialised.</p>
<h3>__clone</h3>
<p>We looked at an example of using the clone keyword in the second part of my introduction to OOP in PHP, to make a copy of an object rather than have two variables pointing to the same actual data. By overriding this method in a class, we can affect what happens when the clone keyword is used on this object. </p>
<p>While this isn&#8217;t something we come across every day, a nice use case is to create a true singleton by adding a private access modifier to the method.</p>
<h3>__toString</h3>
<p>Definitely saving the best until last, the <tt>__toString</tt> method is a very handy addition to our toolkit. This method can be declared to override the behaviour of an object which is output as a string, for example when it is echoed. </p>
<p>For example if you wanted to just be able to echo an object in a template, you can use this method to control what that output would look like. Let&#8217;s look at our Penguin again:</p>
<pre><code>class Penguin {

  public function __construct($name) {
      $this-&gt;species = 'Penguin';
      $this-&gt;name = $name;
  }

  public function __toString() {
      return $this-&gt;name . " (" . $this-&gt;species . ")\n";
  }
}</code></pre>
<p><strong>penguin5.php</strong></p>
<p>With this in place, we can literally output the object by calling echo on it, like this:</p>
<pre><code>$tux = new Penguin('tux');
echo $tux;</code></pre>
<p>I don&#8217;t use this shortcut often but it&#8217;s useful to know that it is there.</p>
<h3>More Magic Methods</h3>
<p>There is a <a href="http://php.net/manual/en/language.oop5.magic.php">great reference on the php.net site </a>itself, listing all the available magic methods (yes, there are more than these, I just picked the ones I actually use) so if you want to know what else is available then take the time to check this out. </p>
<p>Hopefully this has been a useful introduction to the main ones, leave a comment to let us know how you use these in your own projects!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/9-magic-methods-for-php/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>WordPress 3.0 for Web Designers</title>
		<link>http://thinkvitamin.com/code/wordpress-3-0-for-web-designers/</link>
		<comments>http://thinkvitamin.com/code/wordpress-3-0-for-web-designers/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 10:00:21 +0000</pubDate>
		<dc:creator>Richard Shepherd</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=6024</guid>
		<description><![CDATA[Editors Note: In his first article for Think Vitamin Richard Shepherd looks at what&#8217;s new in the upcoming 3.0 release of WordPress and quizzes a number of web designers on their thoughts on the new features. According to founder Matt Mullenweg, WordPress now runs an estimated 8.5% of all sites on the internet. This is [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Editors Note:</strong> In his first article for Think Vitamin Richard Shepherd looks at what&#8217;s new in the upcoming 3.0 release of WordPress and quizzes a number of web designers on their thoughts on the new features.<br />
</em></p>
<p><a href="http://wordpress.org/development/2010/05/wordpress-3-0-release-candidate/"><img class="aligncenter size-full wp-image-6065" style="border: 1px solid #999" src="http://carsonified.com/wp-content/uploads/2010/06/wp30rc1.png" alt="" width="470" height="150" /></a></p>
<p>According to founder <a href="http://ma.tt/">Matt Mullenweg</a>, <a href="http://wordpress.org">WordPress</a> now runs an estimated 8.5% of all sites on the internet. This is a staggering amount &#8211; almost one in every ten sites is sitting on what was once just ‘blogging software’.</p>
<p>Put another way, there are 20 million eager WordPressers looking forward to the long awaited upgrade from 2.9.2 to WordPress 3.0.</p>
<p>The <a href="http://wordpress.org/development/2010/05/wordpress-3-0-release-candidate/">first release  candidate</a> is now available and most of the new features are well-known  and have been described in detail. Others, like custom post types, are leaving  some users scratching their heads. But what does the new version of WordPress  mean for the millions of web designers that use it every day?<span id="more-6024"></span></p>
<h3>A CMS by any Other Name</h3>
<p><em>&#8220;Version 3 is absolutely a step forward for designers&#8221;</em>, argues Chris Coyier from <a href="http://css-tricks.com/">CSSTricks</a>&#8221;</p>
<blockquote><p>&#8220;For one thing, I think it will finally squelch the &#8216;WordPress is a blogging platform, not a CMS&#8217; argument. With custom post types becoming a core feature, it is straight up CMS territory.&#8221;</p></blockquote>
<p>We&#8217;ll come back to custom post types later, but the point that Chris makes about WordPress becoming a true Content Management System (CMS) has lots of support.</p>
<p><a href="http://www.elliotjaystocks.com/">Elliot Jay Stocks</a> is a well-known designer who uses WordPress, and he&#8217;s also excited about this development towards a true CMS:</p>
<blockquote><p>&#8220;It&#8217;s definitely a step forward. It&#8217;s moving further and further away from its roots as a blogging engine and incorporating powerful tools that make it a viable CMS.&#8221;</p></blockquote>
<p><a href="http://perishablepress.com/">Jeff Starr</a>, who co-wrote ‘<a href="http://digwp.com/">Digging into WordPress</a>’, believes that:</p>
<blockquote><p>“WordPress 3 is custom everything, and it&#8217;s awesome. These features provide greater control and flexibility in terms of content organisation, presentation, and management. Custom content types take us beyond the days of posts and pages. Custom taxonomies take us beyond tags and categories.”</p></blockquote>
<p>Adii Pienaar from <a href="http://woothemes.com/">WooThemes</a> agrees:</p>
<blockquote><p>&#8220;I&#8217;m very excited about custom post types as this makes WordPress even more of a fully-fledged CMS”</p></blockquote>
<p>So let&#8217;s take a look at some of these features in more depth, and just how they will affect web professionals designing sites for the WordPress platform.</p>
<h3>Custom Post Types &#8211; Simpler than it Sounds</h3>
<p>Perhaps the feature that causes the most confusion, or at least the most questions, is custom post types. At its heart it&#8217;s a relatively simple concept &#8211; instead of just posts and pages you can now specify your own type of entry.</p>
<p style="text-align: center"><img class="aligncenter size-full wp-image-6054" style="border: 1px solid #999999;margin-bottom: -10px" src="http://carsonified.com/wp-content/uploads/2010/06/wp3_cpt.jpg" alt="" width="470" height="270" /></p>
<p style="text-align: center"><strong><em>Admin screen for a custom post type of &#8220;Video&#8221;</em></strong></p>
<p>Chris from CSSTricks explains the concept well:</p>
<blockquote><p>&#8220;Think of how <a href="http://tumblr.com">Tumblr</a> works – how you can publish photos, quotes, links and whatever else. You could create those same types now with WordPress, and build themes to support and have special styles for them. This is fantastic stuff for building custom sites!&#8221;</p></blockquote>
<p>Fantastic stuff indeed, and it&#8217;s interesting to hear Chris mention Tumblr. WordPress&#8217;s nimbler, younger cousin continues to grow at a phenomenal rate and has many fans out there. Indeed, some designers have ditched WordPress altogether for Tumblr.</p>
<p>Others, like Corbus Bester, have designed amazing WordPress sites that look and feel like <a href="http://fresh01.co.za/">Tumblogs</a>. Perhaps there is some mileage in this fusion of styles; it&#8217;s certainly now possible &#8211; and considerably easier &#8211; with custom post types.</p>
<p>Chris Spooner from <a href="http://www.spoongraphics.co.uk/">SpoonGraphics</a> also sees the benefit this new feature will bring:</p>
<blockquote><p>“As someone who uses WordPress for almost every website I build, I&#8217;d say it would be really useful to be able to create a new entry for a particular section of a website that&#8217;s different to the usual post and page layouts. A new portfolio entry springs to mind as a good use of this feature.”</p></blockquote>
<h3>The Community Gives Back</h3>
<p>One of the other highly publicised additions, thanks in no small part to the goodwill and marketing genius of those WooThemes folk, is the new Navigation System.</p>
<p style="text-align: center"><img class="aligncenter size-full wp-image-6057" style="border: 1px solid #999999;margin-bottom: -10px" src="http://carsonified.com/wp-content/uploads/2010/06/wp3_menus.jpg" alt="" width="470" height="263" /></p>
<p style="text-align: center"><em><strong>Admin screen for the new menu system</strong><br />
</em></p>
<p>It is, in short, a master-stoke. It also blurs the line between the open-source platform and its profit-making community. Adii Pienaar explains:</p>
<blockquote><p>&#8220;I&#8217;m happy to be a bit biased, but the new menu system that WooThemes contributed is long overdue and a massive benefit to every single WordPress user, In essence, this is such a basic feature of any CMS, but due to it being a benefit to all WordPress users I think this is a significant new addition&#8221; he adds.</p></blockquote>
<p>Chris Coyier believes:</p>
<blockquote><p>“The menu building tools are going to be huge for designers as well, and unquestioningly a step forward. Building dynamic menus in the past has involved using WordPress functions in the theme code itself with a bunch of parameters. Nerdy stuff, and not for the average site owner or even for many designers.”</p></blockquote>
<p>WooThemes designer Magnus Jepson agrees:</p>
<blockquote><p>“The navigation system will let designers concentrate on setting up the menu instead of hard coding it.”</p></blockquote>
<p>So how does it work? Chris explains:</p>
<blockquote><p>“The new menu builder puts a GUI on [menu building], putting menu control in the admin where it should be and where anybody can intuitively control it.”</p></blockquote>
<h3>Other Features</h3>
<p>Of the myriad other features on offer with version 3.0, the more noteworthy include:</p>
<ul>
<li>The long awaited integration of <a href="http://mu.wordpress.org/">WordPress MU</a> with the core WordPress code, a project that has taken the WordPress team over a year;</li>
<li>The new default theme <a href="http://2010dev.wordpress.com/">TwentyTen</a>, and the promise of a new theme every year;</li>
<li><a href="http://wpengineer.com/wordpress-3-0-specific-author-templates/">New author templates</a>, allowing the easier customisation of pages for individual authors; and</li>
<li>A new installation system, ditching the known security issue that is the ubiquitous ‘admin’ user.</li>
</ul>
<p style="text-align: center"><img class="aligncenter size-full wp-image-6053" style="border: 1px solid #999999;margin-bottom: -10px" src="http://carsonified.com/wp-content/uploads/2010/06/wp3_2010.jpg" alt="" width="470" height="260" /></p>
<p style="text-align: center"><em><strong>The new default theme &#8220;TwentyTen&#8221; home page</strong><br />
</em></p>
<h3>WordPress 3 for Designers</h3>
<p>So will these new features make a difference for designers? Adii argues:</p>
<blockquote><p><em>&#8220;Not necessarily for designers, </em><em>I think the new features are probably more geared to end-users, like the menu system, or developers, for example custom post types.&#8221;</em></p></blockquote>
<p>He has a point. The level of comfort and experience you have with PHP really does affect how much you can squeeze from the WordPress system; HTML and CSS are simply not enough. Elliot touches on this:</p>
<blockquote><p>&#8220;I hope it becomes easier to work with template files. Less PHP wizardry required and more functionality built in from the start.&#8221;</p></blockquote>
<p>Chris Spooner thinks that others will benefit from the upgrade:</p>
<blockquote><p>“I see the upgrades more suited to the everyday end user. The extra customisation options will also allow the non-tech user to add their own touch to their blog.”</p></blockquote>
<p>Others, like Jeff Starr, believe that WordPress 3 will bring benefits to designers as well<em>:</em></p>
<blockquote><p>“[It is] definitely a step forward. A huge step. In addition to better content management, its integration of WPMU makes it that much easier to create entire networks of sites with a single installation. WordPress 3 also features bulk updates for plug-ins and themes, saving users even more time.”</p></blockquote>
<p>And it’s that hacking that keeps WordPress, even version 3.0, out of the  reach of anyone without a basic grounding in PHP (and, arguably,  jQuery). Elliot argues:</p>
<blockquote><p>&#8220;It still doesn&#8217;t look as powerful as Expression Engine, But for ease-of-setup and ease-of-use, WordPress remains my favourite CMS. My only beef with WordPress is that it can take a lot of hacking to get what you want, and I&#8217;m hoping that WordPress 3 will solve this problem.&#8221;</p></blockquote>
<h3>The future for WordPress</h3>
<p>So just what does the future hold for WordPress? Is it too early to speculate what we&#8217;ll see in WordPress 4?<em></em></p>
<blockquote><p><em>&#8220;I&#8217;d actually vote for it not to develop too much,</em>&#8221; said Adii from WooThemes.<em> &#8220;WordPress is great because it has never been the most complex or complicated system to use. I am however in favour of adding functionality that will make WordPress a more complete CMS, even if that means having different ‘flavours’ of the platform i.e. blogging vs. CMS.&#8221;</em></p></blockquote>
<p>Perhaps <a href="http://wordpress.com">WordPress.com</a> will remain as the hosted solution for casual bloggers, and a ‘WPLite’ version will also become available.</p>
<p>We then might see an offshoot, the more powerful CMS version, which caters for the needs of its considerable and growing user-base of web designers looking for a back-end system.</p>
<p>It makes sense, and it could see an opportunity for <a href="http://automattic.com">Automattic</a> to further monetise part of its software-as-service stable. But who exactly would profit? And who would pay?</p>
<p>When asked about the future or WordPress, Jeff focuses on usability for designers:<em></em></p>
<blockquote><p><em>“Make it fast, make it secure, and make it easy on the server. Go for lean and mean, and deprecate the fluff that nobody uses.”</em></p></blockquote>
<p>This sentiment is echoed by Magnus:</p>
<blockquote><p><em>“I hope that WordPress will develop to be faster and more secure than it is today, and also that it adopts the most widely used functions into the core for all to use. Maybe wishful thinking to have both new functions and faster system, but everything is possible.”</em></p></blockquote>
<p>Chris Coyier also offers some thoughts about the future:<em></em></p>
<blockquote><p><em>&#8220;As far as the software itself, I hope it continues to have a big community and have a good, smart, quick core team. There are no particular ‘features’ that I&#8217;m pining for anymore, mostly just a wish that the team keeps my WordPress nice and secure as we move forward.&#8221;</em></p></blockquote>
<p>There&#8217;s a nice turn of phrase here from Chris, &#8220;My WordPress&#8221;. The wonderful thing about WordPress is that it’s us, the users, the designers and the developers that help create its ultimate direction. And it’s our creative and unique implementations of this powerful system that will guide its future development.</p>
<h3>Want More on WordPress 3.0?</h3>
<p>Over the coming weeks we will be taking a more code based look at some of the new features in WordPress 3.0. Watch out for our first article which will focus on &#8220;Custom Posts&#8221; in the next few weeks.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/wordpress-3-0-for-web-designers/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Getting Started with OOP &amp; PHP5: Part 2</title>
		<link>http://thinkvitamin.com/code/getting-started-with-oop-php5-part-2/</link>
		<comments>http://thinkvitamin.com/code/getting-started-with-oop-php5-part-2/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 10:00:36 +0000</pubDate>
		<dc:creator>Lorna Jane Mitchell</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=5203</guid>
		<description><![CDATA[This post follows on from my first article &#8220;Getting Started with OOP &#38; PHP5&#8221; which introduced the basics of Object Orientated Programming and what that looks like in PHP. This time around we&#8217;ll look at some more advanced concepts and some more practical examples of building code, covering use of constructors and how to add [...]]]></description>
			<content:encoded><![CDATA[<p>This post follows on from my first article &#8220;<a title="Getting Started with OOP &amp; PHP5" rel="bookmark" href="/blog/dev/getting-started-with-oop-php5/">Getting Started with OOP &amp; PHP5</a>&#8221; which introduced the basics of Object Orientated Programming and what that looks like in PHP.</p>
<p>This time around we&#8217;ll look at some more advanced concepts and some more practical examples of building code, covering use of constructors and how to add access modifiers in to control how calling code can operate on your objects.</p>
<p>We&#8217;ll also show off how to create static methods and properties and, perhaps more importantly, illustrate applications of these features.<br />
<span id="more-5203"></span></p>
<h3>Constructors</h3>
<p>Let&#8217;s start at the very beginning, and look at what happens when we create an object.  When a class is instantiated and used to create an object, a particular function is run and this is called the constructor.  The way this is done changed between PHP version and so can be a bit confusing.</p>
<p>In PHP 4, the constructor was a function with the same name as the class itself &#8211; and although PHP 4 is dead and gone (deprecated and no longer supported even for security fixes), that behaviour has been preserved in PHP 5 to preserve backwards compatibility, and you will still see it in code which transitioned between the language versions.  Here is an example:</p>
<pre><code>class Penguin {

public function penguin($name) {
$this-&gt;name = $name;
$this-&gt;type = "penguin";
return true;
}

}</code></pre>
<p><strong>penguin_deprecated.php</strong></p>
<p>So in PHP 5, this would still work, but really we want to use the magic methods introduced in that version, where the constructor is called <tt>__construct()</tt> and our class would then look like this:</p>
<pre><code>class Penguin {

public function __construct($name) {
$this-&gt;name = $name;
$this-&gt;type = "penguin";
return true;
}

}</code></pre>
<p><strong>penguin.php</strong></p>
<p>The PHP 5 version makes more sense because the method can then be inherited, rather than having to redeclare a same-named function and call the function which matches the name of the extending class?  Confused?  Me too :)  Always use <tt>__construct()</tt> is the main message here.</p>
<h3>The Static Keyword</h3>
<p>So far we&#8217;ve looked at fairly classic OO concepts, but to take full advantage of the functionality on offer, there are some more tricks we can learn.  One of my favourites (in fact I probably use it too much!) is the <tt>static</tt> keyword.</p>
<p>The static keyword can be applied to both properties and methods, and we literally mean &#8220;static&#8221; in this case as to mean &#8220;the opposite of dynamic&#8221;.  When we use static properties and methods, we use the class as it stands, without instantiating it.  Sounds a bit strange so let&#8217;s take a look at some examples.</p>
<h3>Static Properties</h3>
<p>A static property is something we can set on an object, either from inside it or from outside, and retrieve it later.  It is almost like a constant, something we use for reference, except that it isn&#8217;t constant and we can change it at any time.</p>
<p>If you are familiar with using static variables in procedural PHP, then this is a concept that will come easily to you.  An example:</p>
<pre><code>class Message {
public static $system_name = 'Default';
}</code></pre>
<p><strong>message.php</strong></p>
<p>This is a very simple class, with a single static property declared.  As with all class properties, these can be created and used on the fly since there is no requirement to declare these in PHP.</p>
<p>To access this property, we do not need to instantiate an object of this type.  Instead we use the class name followed by the &#8220;<tt>scope resolution operator</tt>&#8221; which is two colons, and then the usual dollar sign and variable name we want, like this:</p>
<pre><code>include('message.php');

echo Message::$system_name;</code></pre>
<p>We can modify this variable from outside as shown in the following example, which also illustrates that this property is NOT set on an object instantiated from this class definition:</p>
<pre><code>include('message.php');

Message::$system_name = 'Social Network Messaging';

$msg = new Message();
var_dump($msg-&gt;system_name);

echo Message::$system_name;</code></pre>
<p>This script outputs NULL followed by &#8220;Social Network Messaging&#8221;, as we&#8217;d expect.</p>
<h3>Static Methods</h3>
<p>Static methods follow the same sort of ideas as static properties.  They are declared using the static keyword alongside the access modifier (traditionally after it but either order is valid), and they do not require the class to be instantiated.</p>
<p>Static methods are useful for situations where you don&#8217;t need any other information to perform the task.  For example they are common in the search methods on an object; &#8220;findItemByProductId&#8221; could be a static method that retrieves some data and then instantiates an object and returns it.</p>
<p>Here&#8217;s an example of a simple <tt>inflector</tt> method; we might want to keep a bunch of these methods together but we don&#8217;t need an instantiated object to use them:</p>
<pre><code>class Inflector {
public static function pluralise($word) {
if($word == "sheep") {
$plural = "sheep";
} elseif (substr($word, -1) == 'y') {
$plural = substr($word,0,-1) . 'ies';
} else {
$plural = $word . 's';
}

return $plural;
}
}</code></pre>
<p><strong>inflector.php</strong></p>
<p>When we use this static method we once again use the scope resolution operator:</p>
<pre><code>include('inflector.php');

echo Inflector::pluralise('tree') . "\n";
echo Inflector::pluralise('story') . "\n";
echo Inflector::pluralise('sheep') . "\n";</code></pre>
<p>This script outputs &#8220;trees&#8221;, &#8220;stories&#8221; and &#8220;sheep&#8221; as we&#8217;d expect &#8211; we don&#8217;t need any settings on the objects itself so we never use <tt>$this</tt>, which is why this makes a good example of using a static class.</p>
<h3>Objects, Storage and References</h3>
<p>A big change between earlier versions of PHP and PHP 5 is that objects are always passed by reference now, in fact every object is stored simply as a pointer.</p>
<p>This is useful since any changes made to an object passed into a function will persist without us having to pass it back, but it does mean that we can sometimes be tripped up when working with objects and particularly copying them.</p>
<h3>Using Clone</h3>
<p>So look at this example, what would you expect the output to be?</p>
<pre><code>$a = new stdClass();
$a-&gt;name = 'Alice';
$b = $a;
$b-&gt;name = 'Beatrice';

echo $a-&gt;name;</code></pre>
<p>In fact this example prints &#8220;Beatrice&#8221;.  This is because when we do <tt>$b = $a</tt> we aren&#8217;t copying the values.  We&#8217;re telling <tt>$b</tt> that it should point to the same collection of data that $a is pointing to, because objects are just references.</p>
<p>If we want <tt>$b</tt> to be separate from <tt>$a</tt> then we will need to make use of the clone keyword, as shown here, only the line where we create <tt>$b</tt> changes.</p>
<pre><code>
$a = new stdClass();
$a-&gt;name = 'Alice';
$b = clone($a);
$b-&gt;name = 'Beatrice';

echo $a-&gt;name;</code></pre>
<p>This time the script outputs &#8220;Alice&#8221; &#8211; our changes to <tt>$b</tt> don&#8217;t affect the values in <tt>$a</tt>.</p>
<p>As I mentioned before, this change of handling happened between PHP 4 and PHP 5 &#8211; and certainly caused some headaches for those that upgraded.  However the current behaviour really does work well so it was a good decision in the longer term.</p>
<h3>Comparing Objects</h3>
<p>Having just said that objects are purely references, we need to bear this in mind when we compare objects &#8211; because objects with the same properties set to the same values evaluate differently to two variables pointing to the same object.</p>
<p>For two objects that are of the same types and have all the same property values, we can use the comparison operator &#8220;<tt>==</tt>&#8220;.  To identify where the same object is being referred to, we can use a strict comparison &#8220;<tt>===</tt>&#8221; to evaluate this.</p>
<h3>A Question of Class</h3>
<p>If you have an object and you want to assess what kind of an object it is, you can do this using the <tt>InstanceOf</tt> operator.  If we go back and use our penguin class from earlier, we can try this out:</p>
<pre><code>include('penguin.php');

$tux = new Penguin("Tux");

if($tux InstanceOf Penguin) {
echo "I'm a penguin\n";
} else {
echo "I don't know what I am\n";
}</code></pre>
<p>Note that since it is an operator, it goes between the object we are assessing and what we want it to be, just like the other operators, such as the less than.  Objects will return true to <tt>InstanceOf</tt> evaluation if they are of that class, implement that class, or extend that class &#8211; a very powerful way of identifying if a class will match your needs.</p>
<h3>In Conclusion</h3>
<p>This article has covered some tools for use of OOP in PHP which I hope will bring you to a point where you feel ready to use this in applications of your own.</p>
<p>A lot of the concepts covered here you might not need every day &#8211; but they might catch you out so bookmark this article for reference and refer back any time you need a quick reminder.  If you&#8217;re using these techniques then do share your tips with other readers in the comments!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/getting-started-with-oop-php5-part-2/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Getting Started with OOP &amp; PHP5</title>
		<link>http://thinkvitamin.com/code/getting-started-with-oop-php5/</link>
		<comments>http://thinkvitamin.com/code/getting-started-with-oop-php5/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 10:00:05 +0000</pubDate>
		<dc:creator>Lorna Jane Mitchell</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=5019</guid>
		<description><![CDATA[Since the introduction of PHP 5 in 2004, PHP has had an object model worthy of that description and became a truly modern language for use on the web. Earlier PHP scripts would have been of the kind where, to quote from Alice&#8217;s Adventures, you would &#8220;Begin at the beginning, and go on till you [...]]]></description>
			<content:encoded><![CDATA[<p>Since the introduction of PHP 5 in 2004, PHP has had an object model worthy of that description and became a truly modern language for use on the web.  Earlier PHP scripts would have been of the kind where, to quote from Alice&#8217;s Adventures, you would &#8220;Begin at the beginning, and go on till you come to the end: then stop.&#8221;</p>
<p>Nowadays that very procedural approach is less common in PHP, so this article takes a look at some of the basic object oriented features available in the language and shows some examples of using them with code examples.</p>
<p><span id="more-5019"></span></p>
<p>Using OOP (Object Orientated Programming) enables us to architect our systems much more clearly, and to make them more manageable and more maintainable.  This technique also allows us to separate form from function to create clean, navigable codebases with plenty of opportunities to reuse code, apply design patterns and bring in concepts from other brances of computer science.</p>
<h3>Objects vs Classes</h3>
<p>While the terms &#8220;object&#8221; and &#8220;class&#8221; are often used almost interchangeably in the world of software, there is a definite conceptual difference between the two.  A class is the blueprint or recipe; it describes what the object should be, have and do.  So a class might look like this:</p>
<p style="text-align: center;"><a href="http://carsonified.com/wp-content/uploads/2010/03/elephpant.jpg"><img class="aligncenter size-full wp-image-5271" style="border: 1px solid #999;" title="elephpant" src="http://carsonified.com/wp-content/uploads/2010/03/elephpant.jpg" alt="" width="470" height="353" /></a></p>
<pre><code>class Elephpant {
    public $colour;

    public function dance() {
        echo "elephpant dances!\n";
        return true;
    }
}</code></pre>
<p><strong>elephpant.php</strong></p>
<p>An object, on the other hand, is an actual instantiation of the class &#8211; its an actual thing, with values and behaviours.  In the example below, $ele is the object:</p>
<pre><code>include('elephpant.php');

$ele = new Elephpant();
</code></pre>
<p>We can inspect $ele to make sure that it is, in fact, an object of the class Elephpant, using the <tt><a href="http://uk2.php.net/manual/en/function.print-r.php">print_r</a></tt> command.  Adding this to our code sample as shown, we see the output below:</p>
<pre><code>include('elephpant.php');

$ele = new Elephpant();
print_r($ele);

Elephpant Object
(
    [colour] =&gt;
)</code></pre>
<p>This output shows an object, of type Elephpant, and with a single empty property named &#8220;colour&#8221;.  For more information about the objects exact properties and their values, you can also use <tt><a href="http://uk2.php.net/manual/en/function.var-dump.php">var_dump</a></tt>, which gives a more detailed output showing in detail the datatypes of each property.  This is particularly useful for spotting empty strings, nulls and false.</p>
<h3>Using Objects, Their Properties and Methods</h3>
<p>Our class, Elephpant, has a property and a method (OO-speak for &#8220;function&#8221;) already defined inside it, so how can we interact with these?  Let&#8217;s start by setting the colour property; we use the object operator which is a hyphen followed by a greater than sign.</p>
<pre><code>include('elephpant.php');

$ele = new Elephpant();

// set the colour property
$ele-&gt;colour = "blue";

// now use that property
echo "The elephpant is " . $ele-&gt;colour;
</code></pre>
<p>The output of this script reads &#8220;The elephpant is blue&#8221;.  The property will remain set on the object until the object is destroyed, or the property overwritten or unset.  Objects are a great way of keeping things together that belong together, for example information about an elephpant!</p>
<p>Similarly we can call the method using the same operator &#8211; the brackets after the call let PHP know its a method rather than a property, and if we had parameters to pass in they&#8217;d go between the brackets.  Something like this:</p>
<pre><code>include('elephpant.php');

$ele = new Elephpant();

// call the dance method
$ele-&gt;dance();</code></pre>
<p>Look back at the class declaration for Elephpant and you&#8217;ll see the dance method actually echoes from within it.  Indeed when we run the code example here, we see &#8220;elephpant dances!&#8221; as our output.  It is a very trivial example but I hope it does show how to call methods against our objects.  An alternative approach (and probably a better one within an actual application) would be to create the string and use it as the return value for the function.  Then the calling code can take the string and echo it, or do whatever else it needs to, in a more flexible way.</p>
<h3>Inheritance</h3>
<p>Now we know how to create and interact with objects, let&#8217;s step things up a bit and look at how we can create objects which are similar in some ways and different in others, using inheritance.  If you are accustomed to OOP from any other programming languages then this will seem very familiar to you, so here is a quick look at how this can be done in PHP. We already have our Elephpant class declared, so let&#8217;s add a Penguin class as well.  They will both inherit from the parent class Animal, which looks like this:</p>
<pre><code>class Animal{

    public $type = "animal";

    public function dance() {
        echo $this-&gt;type . " dances!\n";
        return true;
    }
}</code></pre>
<p><strong>animal.php</strong></p>
<p>The animal has a &#8220;type&#8221; property, and a dance() method.  It uses the type property in the dance() method to create the output, using $this to refer to the current object.  In PHP, $this is a special keyword which refers to the current object from within its own class.</p>
<p style="text-align: center;"><a href="http://carsonified.com/wp-content/uploads/2010/03/penguin.jpg"><img class="aligncenter size-full wp-image-5272" style="border: 1px solid #999999;" title="penguin" src="http://carsonified.com/wp-content/uploads/2010/03/penguin.jpg" alt="" width="470" height="353" /></a></p>
<p>Now we can create a Penguin class that inherits from this general Animal class, by using the extends keyword to denote its parent:</p>
<pre><code>class Penguin extends Animal {
    public $type = "penguin";
}</code></pre>
<p><strong>penguin.php</strong></p>
<p>The penguin class would inherit the type property set to &#8220;animal&#8221; if we didn&#8217;t override it by setting the property again in this class.  However even without declaring a dance() method, the penguin can dance!</p>
<pre><code>include('animal.php');
include('penguin.php');

$tux = new Penguin();

// make tux dance
$tux-&gt;dance();</code></pre>
<p>The above example gives the output &#8220;penguin dances!&#8221; &#8211; using the dance() method from the Animal class, which is available because the Penguin class extends it, and the type property set separately in the Penguin class itself.</p>
<h3>Access Modifiers</h3>
<p>Take a look at the previous example.  The type is set in the class, but we could easily set it from our main code if we wanted to.  Imagine if we put $tux-&gt;type = &#8220;giraffe&#8221; before we asked him to dance!  Sometimes this is the desired behaviour, and sometimes it isn&#8217;t.  To allow us to control whether properties can be changed outside a class, PHP gives us access modifiers.  An example of these are the &#8220;public&#8221; keywords you see in the classes shown above.  To prevent the type property being edited from outside the class, we can declare the Penguin type to be private, so the class now looks like this:</p>
<pre><code>class Penguin extends Animal {
    private $type = "penguin";
}</code></pre>
<p><strong>private_penguin.php</strong></p>
<p>The following code listing shows us trying to set the now-private type property, and is followed by the resulting output.</p>
<pre><code>include('animal.php');
include('private_penguin.php');

$tux = new Penguin();

// change the type
$tux-&gt;type = "linux penguin";
// make tux dance
$tux-&gt;dance();

Fatal error: Access level to Penguin::$type must be public (as in class Animal) in /home/lorna/.../OOP/private_penguin.php on line 5</code></pre>
<p>The resulting message feeds back to the user that the type property can&#8217;t be modified, and even includes the detail that the property was public in the parent class.  Access modifiers are pretty powerful, we should look at them in more detail.</p>
<p>Access modifiers can be applied to properties and to methods and to properties.  The options are public, private and protected.  In PHP4, these weren&#8217;t available and everything is public.  As a result, and to maintain backwards compatibility, if an access modifier isn&#8217;t specified then the property or method defaults to being public.  This isn&#8217;t recommended practice however, and it is best to be explicit about which is intended.</p>
<p><strong>Public:</strong> The public access modifier means that properties and methods can be accessed from anywhere, within the scope of the object itself, and also from outside code operating on an object.</p>
<p><strong>Private: </strong>The method or property is only available from within the scope of this specific class.  Before using this option, read on to find out about the &#8220;protected&#8221; access modifier.</p>
<p><strong>Protected: </strong>The method or property is available from within this class, and from within any classes with extend or implement this class.  This is ideal where you don&#8217;t want external code to change the class, but you do want to be able to extend the class later and take advantage of this property or method.  Protected is more flexible than private and almost always the better choice.</p>
<p>Using these access modifiers we can control where our class methods and properties can be accessed from.  We looked at an example of properties and this works in the same way for method calls &#8211; they cannot be accessed from outside of the class definition unless they are declared to be public.  It can be very useful indeed to declare methods as protected, where they are internal helper methods used by other class methods but not intended to be accessed directly.  In PHP4 there was no support for this and so the internal methods were sometimes named with an underscore to hint that this was their intended use &#8211; it is still possible to see this naming convention in use today, although it is not needed.</p>
<h3>Using OOP in PHP: Practical Example</h3>
<p>Object Oriented design is particularly useful where you have data objects that relate to one another &#8211; so it is very common for example to have OOP used to deal with data.  PHP 5 has the <a href="http://uk2.php.net/manual/en/book.pdo.php">PDO (PHP Data Object)</a> classes which are a great way to talk to a backend database, either mysql or any other kind of database, and using the object oriented interface offered by this extension ties in well with the usage I have shown here.</p>
<p>A common mistake for those coming to OO for the first time is to declare methods inside a class but then instantiate a single copy of that and pass in data such as the ID of the data to each method.  Here&#8217;s an example of a user class that does this:</p>
<pre><code>class User {
    /**
     * getDisplayName
     *
     * @param int $user_id the user_id of the user in the database table
     * @access public
     * @return string Display name of this user
     */
    public function getDisplayName($user_id) {
        $sql = 'select display_name from users where user_id = '.$user_id;
        $results = mysql_query($sql);
        $row = mysql_fetch_array($results);
        return $row['display_name'];
    }

    /**
     * getFriends
     *
     * @param int $user_id the user_id of the user in the database table
     * @access public
     * @return array An array of friend_ids
     */
    public function getFriends($user_id) {
        $sql = 'select friend_id from user_friends where user_id = '.$user_id;
        $results = mysql_query($sql);
        $friends = array();
        while($row = mysql_fetch_array($results)) {
            $friends[] = $row['friend_id'];
        }
        return $friends;
    }
}</code></pre>
<p><strong>user.php</strong></p>
<p>And some code that uses it:</p>
<pre><code>include('user.php');
mysql_connect('localhost','root','');
mysql_select_db('test');

$user = new User();
echo "User known as: " . $user-&gt;getDisplayName(1) . "\n";

$friends = $user-&gt;getFriends(1);
echo "Friends with: " . implode(', ',$friends) . "\n";</code></pre>
<p>If you want to run this code yourself, then you can set up the database tables using this script:</p>
<pre><code>CREATE TABLE `user_friends` (
  `user_friend_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `friend_id` int(11) NOT NULL,
  PRIMARY KEY (`user_friend_id`)
)
INSERT INTO `user_friends` VALUES (1,1,3),(2,1,5);

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(20) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `display_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
)
INSERT INTO `users` VALUES (1,'Lorna','Mitchell','lornajane');</code></pre>
<p><strong>user.sql</strong></p>
<p>This is more like a function library than an actual object, and although it works perfectly well and does have its applications, it can be better to aim to take advantage of more object oriented features.  To do this, a new object should be created for each item the system handles, and if it has an ID and perhaps some other properties, these should be set as part of the object.  Then rather than creating a single user object and doing getFriends(42) on it, you&#8217;d have a user with ID 42 which did $user-&gt;getFriends().</p>
<p>Here&#8217;s a follow up example with a class and how to use it, this will give better performance and enable you to clearly see which data goes with which object where there are multiple items on a page:</p>
<pre><code>class User {
    /**
     * getUserById
     *
     * @param int $user_id the id of the user row in the table
     * @access public
     * @return true if the user was found
     */
    public function getUserById($user_id) {
        $sql = 'select first_name, last_name, display_name from users where user_id = ' . $user_id;
        $results = mysql_query($sql);
        $row = mysql_fetch_array($results);
        $this-&gt;user_id = $user_id;
        $this-&gt;first_name = $row['first_name'];
        $this-&gt;last_name = $row['last_name'];
        $this-&gt;display_name = $row['display_name'];

        // in real life, there would be escaping and error handling and we'd only return true if we got data
        return true;
    }

    /**
     * getDisplayName
     *
     * @access public
     * @return string Display name of this user
     */
    public function getDisplayName() {
        return $this-&gt;display_name;
    }

    /**
     * getFriends
     *
     * @access public
     * @return array An array of friend_ids
     */
    public function getFriends() {
        $sql = 'select friend_id from user_friends where user_id = '.$this-&gt;user_id;
        $results = mysql_query($sql);
        $friends = array();
        while($row = mysql_fetch_array($results)) {
            $friends[] = $row['friend_id'];
        }
        return $friends;
    }
}</code></pre>
<p><strong>user2.php</strong></p>
<pre><code>include('user2.php');
mysql_connect('localhost','root','');
mysql_select_db('test');

$user = new User();
// populate the object
$user-&gt;getUserById(1);
echo "User known as: " . $user-&gt;getDisplayName() . "\n";

$friends = $user-&gt;getFriends();
echo "Friends with: " . implode(', ',$friends) . "\n";</code></pre>
<h3>In Summary</h3>
<p>This has been a very introductory look at some of the object oriented features available in PHP, to get you started out with the basics of working with OO code and also writing your own.  If this has helped you take your first OOP steps, then let us know by leaving a comment and let us know what you built!  In the next post there will be some more in-depth content including using constructors, access modifiers and working with the static keyword in PHP &#8211; taking your skills to the next level.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/getting-started-with-oop-php5/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
		</item>
		<item>
		<title>How to Debug in PHP</title>
		<link>http://thinkvitamin.com/code/how-to-debug-in-php/</link>
		<comments>http://thinkvitamin.com/code/how-to-debug-in-php/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 06:00:31 +0000</pubDate>
		<dc:creator>Kieran Masterton</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=3037</guid>
		<description><![CDATA[Nobody enjoys the process of debugging their code. If you want to build killer web apps though, it&#8217;s vital that you understand the process thoroughly. This article breaks down the fundamentals of debugging in PHP, helps you understand PHP&#8217;s error messages and introduces you to some useful tools to help make the process a little [...]]]></description>
			<content:encoded><![CDATA[<p>Nobody enjoys the process of debugging their code. If you want to build killer web apps though, it&#8217;s vital that you understand the process thoroughly.</p>
<p>This article breaks down the fundamentals of debugging in PHP, helps you understand PHP&#8217;s error messages and introduces you to some useful tools to help make the process a little less painful.</p>
<p><em>Editor&#8217;s Note: We&#8217;ll be running workshops like &#8220;How to Build a Web App from A-Z&#8221; at <a href="http://events.carsonified.com/fowa/2009/london/workshops#workshop_53?utm_source=TV&#038;utm_medium=Text%2Blink&#038;utm_campaign=How%2Bto%20Debug%20in%20PHP">The Future of Web Apps London</a>.</em></p>
<p><span id="more-3037"></span></p>
<h3>Doing your Ground Work</h3>
<p>It is important that you configure PHP correctly and write your code in such a way that it produces meaningful errors at the right time. For example, it is generally good practice to turn on a verbose level of error reporting on your development platform. This probably isn&#8217;t such a great idea, however, on your production server(s). In a live environment you neither want to confuse a genuine user or give malicious users too much information about the inner-workings of your site.</p>
<p>So, with that in mind lets talk about the all too common &#8220;I&#8217;m getting no error message&#8221; issue. This is normally caused by a syntax error on a platform where the developer has not done their ground work properly. First, you should turn display_errors on. This can be done either in your php.ini file or at the head of your code like this:</p>
<p><code>&lt;?php<br />
ini_set('display_errors', 'On');</code></p>
<p><em>Tip: In these code examples I omit the closing (?&gt;) PHP tag. It is <a href="http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html#coding-standard.php-file-formatting.general" title="Zend Coding Standards">generally considered good practice</a> to do so in files which contain only PHP code in order to avoid accidental injection of white space and the all too common &#8220;headers already sent&#8221; error.</em></p>
<p>Next, you will need to set an error reporting level. As default PHP 4 and 5 do not show PHP notices which can be important in debugging your code (more on that shortly). Notices are generated by PHP whether they are displayed or not, so deploying code with twenty notices being generated has an impact upon the overhead of your site. So, to ensure notices are displayed, set your error reporting level either in your php.ini or amend your runtime code to look like this:</p>
<p><code>&lt;?php<br />
ini_set('display_errors', 'On');<br />
error_reporting(E_ALL);</code></p>
<p><em>Tip: E_ALL is a constant so don&#8217;t make the mistake of enclosing it in quotation marks.</em></p>
<p>With PHP 5 it&#8217;s also a good idea to turn on the E_STRICT level of error reporting. E_STRICT is useful for ensuring you&#8217;re coding using the best possible standards. For example E_STRICT helps by warning you that you&#8217;re using a deprecated function. Here&#8217;s how to enable it at runtime:</p>
<p><code>&lt;?php<br />
ini_set('display_errors', 'On');<br />
error_reporting(E_ALL | E_STRICT);</code></p>
<p>It is also worth mentioning that on your development platform it is often a good idea to make these changes in your php.ini file rather than at the runtime. This is because if you experience a syntax error with these options set in your code and not in the php.ini you may, depending on your set up, be presented with a blank page. Likewise, it is worth noting that if you&#8217;re setting these values in your code, a conditional statement might be a good idea to avoid these settings accidentally being deployed to a live environment.</p>
<h3>What Type of Error am I Looking at?</h3>
<p>As with most languages, PHP&#8217;s errors may appear somewhat esoteric, but there are in fact only four key types of error that you need to remember:</p>
<p><strong>1. Syntax Errors</strong></p>
<p>Syntactical errors or parse errors are generally caused by a typo in your code. For example a missing semicolon, quotation mark, brace or parentheses. When you encounter a syntax error you will receive an error similar to this:</p>
<p><code><strong>Parse error:</strong> syntax error, unexpected T_ECHO in /Document/Root/example.php on line 6</code></p>
<p>In this instance it is important that you check the line above the line quoted in the error (in this case line 5) because while PHP has encountered something unexpected on line 6, it is common that it is a typo on the line above causing the error. Here&#8217;s an example:</p>
<p><code>&lt;?php<br />
ini_set('display_errors', 'On');<br />
error_reporting(E_ALL);<br/><br/><br />
$sSiteName = "Think Vitamin"<br />
echo $sSiteName;</code></p>
<p>In this example I have omitted the semi-colon from line 5, however, PHP has reported an error occurred on line 6. Looking one line above you can spot and rectify the problem.</p>
<p><em>Tip: In this example I am using <a href="http://en.wikipedia.org/wiki/Hungarian_notation" title="Wikipedia entry for Hungarian Notation">Hungarian Notation</a>. Adopting this coding standard can aid with debugging code while working collaboratively or on a piece of code you wrote some time ago. The leading letter denoting the variable type means that determining a variable type is very quick and simple. This can aid in spotting irregularities which can also help highlight any potential logic errors.</em></p>
<p><strong>2. Warnings</strong></p>
<p>Warnings aren&#8217;t deal breakers like syntax errors. PHP can cope with a warning, however, it knows that you probably made a mistake somewhere and is notifying you about it. Warnings often appear for the following reasons:</p>
<ol>
<li>Headers already sent. Try checking for white space at the head of your code or in files you&#8217;re including.</li>
<li>You&#8217;re passing an incorrect number of parameters to a function.</li>
<li>Incorrect path names when including files.</li>
</ol>
<p><strong>3. Notices</strong></p>
<p>Notices aren&#8217;t going to halt the execution of your code either, but they can be very important in tracking down a pesky bug. Often you&#8217;ll find that code that&#8217;s working perfectly happily in a production environment starts throwing out notices when you set error_reporting to E_ALL.</p>
<p>A common notice you&#8217;ll encounter during development is:</p>
<p><code>><strong>Notice:</strong> Undefined index: FullName in /Document/Root/views/userdetails.phtml on line 55</code></p>
<p>This information can be extremely useful in debugging your application. Say you&#8217;ve done a simple database query and pulled a row of user data from a table. For presentation in your view you&#8217;ve assigned the details to an array called $aUserDetails. However, when you echo $aUserDetails['FirstName'] on line 55 there&#8217;s no output and PHP throws the notice above. In this instance the notice you receive can really help.</p>
<p>PHP has helpfully told us that the FirstName key is undefined so we know that this isn&#8217;t a case of the database record being NULL. However, perhaps we should check our SQL statement to ensure we&#8217;ve actually retrieved the user&#8217;s first name from the database. In this case the notice has helped us rule out a potential issue which has in turn steered us towards the likely source of our problem. Without the notice our likely first stop would have been the database record, followed by tracing back through our logic to eventually find our omission in the SQL.</p>
<p><strong>4. Fatal Errors</strong></p>
<p>Fatal Errors sound the most painful of the four but are in fact often the easiest to resolve. What it means, in short, is that PHP understands what you&#8217;ve asked it to do but can&#8217;t carry out the request. Your syntax is correct, you&#8217;re speaking its language but PHP doesn&#8217;t have what it needs to comply. The most common fatal error is an undefined class or function and the error generated normally points straight to the root of the problem:</p>
<p><code><strong>Fatal error:</strong> Call to undefined function create() in /Document/Root/example.php on line 23</code></p>
<h3>Using var_dump() to Aid Your Debugging</h3>
<p>var_dump() is a native PHP function which displays structured, humanly readable, information about one (or more) expressions. This is particularly useful when dealing with arrays and objects as var_dump() displays their structure recursively giving you the best possible picture of what&#8217;s going on. Here&#8217;s an example of how to use var_dump() in context:</p>
<p>Below I have created an array of scores achieved by users but one value in my array is subtly distinct from the others, var_dump() can help us discover that distinction.</p>
<pre><code>&lt;?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);<br/><br/>
$aUserScores = array('Ben' => 7,'Linda' => 4,'Tony' => 5,'Alice' => '9');
echo '&lt;pre&gt;';
var_dump($aUserScores);
echo '&lt;/pre&gt;';</code></pre>
<p><em>Tip: Wrap var_dump() in &lt;pre&gt; tags to aid readability.</em></p>
<p>The output from var_dump() will look like this:</p>
<pre><code>array(4) {
  ["Ben"]=>
  int(7)
  ["Linda"]=>
  int(4)
  ["Tony"]=>
  int(5)
  ["Alice"]=>
  string(1) "9"
}</code></pre>
<p>As you can see var_dump tells us that $aUserScores is an array with four key/value pairs. Ben, Linda, and Tony all have their values (or scores) stored as integers. However, Alice is showing up as a string of one character in length.</p>
<p>If we return to my code, we can see that I have mistakenly wrapped Alice&#8217;s score of 9 in quotation marks causing PHP to interpret it as a string. Now, this mistake won&#8217;t have a massively adverse effect, however, it does demonstrate the power of var_dump() in helping us get better visibility of our arrays and objects.</p>
<p>While this is a very basic example of how var_dump() functions it can similarly be used to inspect large multi-dimensional arrays or objects. It is particularly useful in discovering if you have the correct data returned from a database query or when exploring a JSON response from say, Twitter:</p>
<p><code>&lt;?php<br />
ini_set('display_errors', 'On');<br />
error_reporting(E_ALL);<br/><br/><br />
$sJsonUrl = 'http://search.twitter.com/trends.json';<br/><br/><br />
$sJson = file_get_contents($sJsonUrl,0,NULL,NULL);<br />
$oTrends = json_decode($sJson);<br/><br/><br />
echo '&lt;pre&gt;';<br />
var_dump($oTrends);<br />
echo '&lt;/pre&gt;';</code></p>
<h3>Useful Tools to Consider when Debugging</h3>
<p>Finally, I want to point out a couple of useful tools that I&#8217;ve used to help me in the debugging process. I won&#8217;t go into detail about installing and configuring these extensions and add-ons, but I wanted to mention them because they can really make our lives easier.</p>
<p><strong>Xdebug</strong></p>
<p><a href="http://www.xdebug.org/" title="Xdebug">Xdebug</a> is a PHP extension that aims to lend a helping hand in the process of debugging your applications. Xdebug offers features like:</p>
<ul>
<li>Automatic stack trace upon error</li>
<li>Function call logging</li>
<li>Display features such as enhanced var_dump() output and code coverage information.</li>
</ul>
<p>Xdebug is highly configurable, and adaptable to a variety of situations. For example, stack traces (which are extremely useful for monitoring what your application is doing and when) can be configured to four different levels of detail. This means that you can adjust the sensitivity of Xdebug&#8217;s output helping you to get granular information about your app&#8217;s activity.</p>
<p>Stack traces show you where errors occur, allow you to trace function calls and detail the originating line numbers of these events. All of which is fantastic information for debugging your code.</p>
<p><em>Tip: As default Xdebug limits var_dump() output to three levels of recursion. You may want to change this in your xdebug.ini file by setting the xdebug.var_display_max_depth to equal a number that makes sense for your needs.</em></p>
<p>Check out <a href="http://www.xdebug.org/docs/install" title="Xdebug installation guide">Xdebug&#8217;s installation guide</a> to get started.</p>
<p><strong>FirePHP</strong></p>
<p>For all you <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" title="FireBug">FireBug</a> fans out there, <a href="http://www.firephp.org/" title="FirePHP">FirePHP</a> is a really useful little PHP library and Firefox add-on that can really help with AJAX development.</p>
<p>Essentially FirePHP enables you to log debug information to the Firebug console using a simple method call like so:</p>
<p><code>&lt;?php<br />
	$sSql = 'SELECT * FROM tbl';<br />
	FB::log('SQL query: ' . $sSql);</code> </p>
<p>In an instance where I&#8217;m making an AJAX search request, for example, it might be useful to pass back the SQL string my code is constructing in order that I can ensure my code is behaving correctly. All data logged to the Firebug console is sent via response headers and therefore doesn&#8217;t effect the page being rendered by the browser.</p>
<p><em>Warning: As with all debug information, this kind of data shouldn&#8217;t be for public consumption. The downside of having to add the FirePHP method calls into your PHP is that before you go live you will either have to strip all these calls out or set up an environment based conditional statement which establishes whether or not to include the debug code.</em></p>
<p>You can install the Firefox add-on at <a href="http://www.firephp.org/" title="FirePHP">FirePHP&#8217;s website</a> and also <a href="http://www.firephp.org/HQ/" title="Fire PHP libs">grab the PHP libs</a> there too. Oh, and don&#8217;t forget if you haven&#8217;t already installed FireBug, <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" title="FireBug">you&#8217;ll need that too</a>.</p>
<h3>In Conclusion &#8230;</h3>
<p>Hopefully during the course of this article you have learned how to do your ground work by preparing PHP for the debugging process; recognise and deal with the four key PHP error types and use var_dump() to your advantage. Likewise, I hope that you will find Xdebug and FirePHP useful and that they will make your life easier during your development cycle. </p>
<p>As I&#8217;ve already mentioned, and I really can&#8217;t say this enough, always remember to remove or suppress your debug output when you put your sites into production after all there&#8217;s nothing worse than all your users being able to read about your errors in excruciating detail.</p>
<p>Got a great debugging tip to share? Do you use a great little PHP extension that makes your bug trapping life easier? Please tell us about them in comments below!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/how-to-debug-in-php/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
		</item>
		<item>
		<title>How to Create Bulletproof Sessions</title>
		<link>http://thinkvitamin.com/code/how-to-create-bulletproof-sessions/</link>
		<comments>http://thinkvitamin.com/code/how-to-create-bulletproof-sessions/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 06:00:56 +0000</pubDate>
		<dc:creator>Robert Hafner</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=2955</guid>
		<description><![CDATA[In the first part of this series we went over how a cookie works and what can be done to secure them. In this section we&#8217;re going to go over ways to add additional security to the session beyond the cookie itself. By the end of this article we will written our own wrapper class [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://events.carsonified.com/fowa/2009/london/schedule?utm_source=TV&amp;utm_medium=banner&amp;utm_campaign=Kevin%2Band%20Gary%20Show"><img src="http://ryancarson.com/uploads/kevin_gary.png" alt="Kevin and Gary show at FOWA London" /></a></p>
<p>In the first part of this series we went over <a href="http://carsonified.com/blog/dev/how-to-create-totally-secure-cookies">how a cookie works and what can be done to secure them</a>. In this section we&#8217;re going to go over ways to add additional security to the session beyond the cookie itself.</p>
<p>By the end of this article we will written our own wrapper class for &#8220;session_start&#8221; that protects  our session from a number of attacks while taking into account some of the unique challenges presented by modern ajax-heavy websites.</p>
<p><span id="more-2955"></span></p>
<h3>Session Specific Attacks</h3>
<p>Through the use of sessions your identity is maintained as you use a website, and just as in real life identity theft is a concern. By taking over your session an attacker would essentially become you on a website, with access to all of the actions, information and privileges that entails.</p>
<p>The main thing that an attacker needs to steal a session is the session ID. There are three ways an attacker normally goings about doing this, all of which can be protected against but are, by default, completely open.</p>
<ul>
<li>Guess the ID: most session handlers generate ids that make this impractical.</li>
<li>Steal the ID: by using malware, sniffing the network, or exploiting javascript exploits attackers can get the value from the cookie itself.</li>
<li>Set the ID: rather than steal or guess the ID an attacker may try and set it to a value they choose.</li>
</ul>
<h3>Starting the Session</h3>
<p>The default session setup is not at all secure by itself, so we&#8217;re going to create a wrapper to add the security we need. To make this code more portable we&#8217;re going to build it as a static function of a php class called SessionManager.</p>
<p>To begin our sessionStart function is going to set the name cookie options for the session. Like all cookies we&#8217;re going to need to make some decisions about what is going to need access to the session ID. Since these options depend on the application itself lets add arguments we can change based on our specific needs. </p>
<p>For security we can hardcode the &#8220;HttpOnly&#8221; argument, as session ids are often the juiciest target for cross site scripting attacks. </p>
<pre><code>class SessionManager
{
   static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
   {
      // Set the cookie name before we start.
      session_name($name . '_Session');

      // Set the domain to default to the current domain.
      $domain = isset($domain) ? $domain : isset($_SERVER['SERVER_NAME']);

      // Set the default secure value to whether the site is being accessed with SSL
      $https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);

      // Set the cookie settings and start the session
      session_set_cookie_params($limit, $path, $domain, $secure, true);
      session_start();
   }
}</code></pre>
<p>Using the new class is as easy as including it and running one line but additional options can make it more restrictive.</p>
<p><code>SessionManage::sessionStart('InstallationName');<br />
SessionManage::sessionStart('Blog_myBlog', 0, '/myBlog/', 'www.site.com');<br />
SessionManage::sessionStart('Accounts_Bank', 0, '/', 'accounts.bank.com', true);</code></p>
<h3>Lock the Session to a Host</h3>
<p>Now that our wrapper class is in place and functional we can start building in additional security by restricting the session to the same IP address and User Agent (or browser) as when the session was first opened. This way if the session ID is stolen or guessed the attacker still has to get ahold of the user agent (admittedly not too difficult if they got the session ID) and somehow find a way to get the same IP address.</p>
<p>These attacks only help if the user is not on the same network. The user agent check only adds minor security, since many attacks that compromise the cookie are going to do the same to the user agent. If an attacker is on the same network as the target there is a good chance they already have the same external IP address, as it is pretty common for a network to use private internal addresses while presenting only a single IP address to the internet. This is why it is important to evaluate the need for SSL.</p>
<p>We&#8217;re going to add these new checks to our class in the function preventHijacking. This function will return false on new sessions or when a session is loaded by a host with a different IP address or browser. preventHijacking will true if the session is valid and false otherwise. This means it will return false not just on malicious attempts but completely new sessions as well.</p>
<pre><code>static protected function preventHijacking()
{
	if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
		return false;

	if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
		return false;

	if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
		return false;

	return true;
}</code></pre>
<p>Now that we have a way to identify hijacking attempts we need to set up a way to respond to them. For us this means two things- clearing out the old session data and inserting the IP address and user agent into the new session.</p>
<pre><code>static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
	...
	session_start();

	if(!self::preventHijacking())
	{
		$_SESSION = array();
		$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
		$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
	}
}</code></pre>
<h3>Session Fixation</h3>
<p>So far we have effectively eliminated the possibility of brute force guessing. We&#8217;ve also made it so any attempts at capturing the session ID would require the attacker to be on the same network as the user in order to take advantage of that ID, while also discussing enforcing SSL to make capturing the session more difficult through traditional means. However, what if the attacker could set the session ID themselves?</p>
<p>By getting the user to follow a link with a session ID in it the attacker can trick the user into starting a session with the ID of the attacker&#8217;s choosing. Rather than guess or steal an ID the attacker will have it right from the start. Many web environments, including PHP, allow session ids to be set through the URL, primarily to get around systems which do not support cookies. Just like with regular cookies the value sent by the client is the value used for the ID, so in this case the value in the URL becomes the session ID.</p>
<p>The solution to this is to change the session ID. How often you do this is tends to be a matter of great debate, but at the bare minimum the ID should be changed when new sessions are created and when the user changes privileges (logs in or out).</p>
<h3>A First Attempt At Regenerating the ID</h3>
<p>Regenerating the ID is fairly simply in php. Deceptively simple one might say. The function &#8220;session_regenerate_id&#8221; lets us tell the system to use a new ID.  It can also optionally delete the old session.</p>
<pre><code>// Leaves old session intact
session_regenerate_id();

// Deletes old session
session_regenerate_id(true);</code></pre>
<p>If you don&#8217;t delete the old session then it is still vulnerable to hijacking and whatever access it had can be granted to an attacker. If you&#8217;re changing the session ID often without deleting the old ones you could be creating more holes by leaving a trail of old, but valid, sessions.</p>
<h3>Regenerating the ID in the World of Ajax</h3>
<p>If an application creates a lot of quick connections to the server some interesting things can happen. PHP, and many other languages, restricts access to the session data to one running script at a time, so if multiple requests come in that try to access the session data the second request (and any other) gets queued up. When the first request changes the ID and deletes the old session the second request still has the old session ID which no longer exists. This results in a third, new session being opened and generally means your user gets logged out.</p>
<p>This bug is ridiculously hard to diagnose as the timing of not just the requests but the ID regeneration has to be just right. In sites that don&#8217;t make requests to the server using javascript this type of bug may never be encountered at all, as the time between page loads is more than long enough for the browser to have updated its session info. For sites that make use of ajax techniques, however, this issue will have a chance of occurring whenever the session ID is changed.</p>
<p>In our final update to the SessionManager class we&#8217;re going to write a fix for this problem. Rather than delete the session immediately when we change the ID, we&#8217;re going to mark the old session as obsolete and mark it to expire in ten seconds. This way any queued up requests will still have access to the expired session but we don&#8217;t have to leave it open forever.</p>
<p>To accomplish this we&#8217;re going to add the regenerateSession function. This function adds the obsolete flag and expiration to the session, regenerates the ID to create the new session and saves them both. It  then reopens the new session and removes the obsolete flag. Unlike our other internal functions we are leaving this one open for use outside the class so that it can be tied into login scripts.</p>
<pre><code>static function regenerateSession()
{
	// If this session is obsolete it means there already is a new id
	if(isset($_SESSION['OBSOLETE']) || $_SESSION['OBSOLETE'] == true)
		return;

	// Set current session to expire in 10 seconds
	$_SESSION['OBSOLETE'] = true;
	$_SESSION['EXPIRES'] = time() + 10;

	// Create new session without destroying the old one
	session_regenerate_id(false);

	// Grab current session ID and close both sessions to allow other scripts to use them
	$newSession = session_id();
	session_write_close();

	// Set session ID to the new one, and start it back up again
	session_id($newSession);
	session_start();

	// Now we unset the obsolete and expiration values for the session we want to keep
	unset($_SESSION['OBSOLETE']);
	unset($_SESSION['EXPIRES']);
}</code></pre>
<p>We need to add another function to check for the obsolete flag and to see if the session has expired.</p>
<pre><code>static protected function validateSession()
{
	if( isset($_SESSION['OBSOLETE']) &amp;&amp; !isset($_SESSION['EXPIRES']) )
		return false;

	if(isset($_SESSION['EXPIRES']) &amp;&amp; $_SESSION['EXPIRES'] &lt; time())
		return false;

	return true;
}</code></pre>
<p>Finally, in the last change to our SessionManager, we need to update our SessionStart function. It needs to call the regenerateSession function on new requests and periodically after that, as well as destroy the session if it is invalid. Here is the complete SessionStart function.</p>
<pre><code>static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
	// Set the cookie name
	session_name($name . '_Session');

	// Set SSL level
	$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);

	// Set session cookie options
	session_set_cookie_params($limit, $path, $domain, $https, true);
	session_start();

	// Make sure the session hasn't expired, and destroy it if it has
	if(self::validateSession())
	{
		// Check to see if the session is new or a hijacking attempt
		if(!self::preventHijacking())
		{
			// Reset session data and regenerate id
			$_SESSION = array();
			$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
			$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
			self::regenerateSession();

		// Give a 5% chance of the session id changing on any request
		}elseif(rand(1, 100) &lt;= 5){
			self::regenerateSession();
		}
	}else{
		$_SESSION = array();
		session_destroy();
		session_start();
	}
}</code></pre>
<h3>Summery</h3>
<p>At times it amazes me how complex something as simple as an ID- what is essentially just a string of random characters- can turn out to be. While you can certainly use this class for all of your own projects here is what you need to remember when building your own session manager.</p>
<p>Session IDs are attacked by guessing, capturing or setting the id. You can protect against this in your own applications by &#8230;</p>
<ul>
<li>Securing the cookie to make stealing the ID harder</li>
<li>Limiting the session to a specific host to make attacks more difficult</li>
<li>Changing the ID when escalating privileges and throughout the session life.</li>
</ul>
<p>Here is the complete <a href="http://ryancarson.com/uploads/securingcookies/Session.class.php.zip">Session.class.php file</a> for your reference.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/how-to-create-bulletproof-sessions/feed/</wfw:commentRss>
		<slash:comments>49</slash:comments>
		</item>
		<item>
		<title>17 Awesome Web Developer Cheat Sheets</title>
		<link>http://thinkvitamin.com/code/17-awesome-web-developer-cheat-sheets/</link>
		<comments>http://thinkvitamin.com/code/17-awesome-web-developer-cheat-sheets/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 07:56:37 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=2805</guid>
		<description><![CDATA[Editor&#8217;s Note: We&#8217;ll be covering Object-Oriented JavaScript, Merb, Rails and more at The Future of Web Apps on Oct 1-2. I am sure we have all been in the situation where we&#8217;ve learned a new piece of software and only a couple of weeks later we&#8217;ve forgotten all but the basic commands. This happened to [...]]]></description>
			<content:encoded><![CDATA[<p><em>Editor&#8217;s Note: We&#8217;ll be covering Object-Oriented JavaScript, Merb, Rails and more at <a href="http://events.carsonified.com/fowa/2009/london?utm_source=TV&amp;utm_medium=Link%2Btext&amp;utm_campaign=17%2BAwesome%20Web%20Developer%20Cheat%20Sheets">The Future of Web Apps</a> on Oct 1-2.</em></p>
<p>I am sure we have all been in the situation where we&#8217;ve learned a new piece of software and only a couple of weeks later we&#8217;ve forgotten all but the basic commands. This happened to me recently when moving back to SVN after working with Git. Thankfully I have a handful of &#8220;cheat sheets&#8221; that I call upon at these times.</p>
<p>Here are a list of cheat sheets I find useful:</p>
<p><span id="more-2805"></span></p>
<h4>Server Side Development</h4>
<ul>
<li><a href="http://www.addedbytes.com/cheat-sheets/php-cheat-sheet/">PHP</a></li>
<li><a href="http://www.addedbytes.com/cheat-sheets/ruby-on-rails-cheat-sheet/">Ruby on Rails</a></li>
<li><a href="http://www.mercurytide.co.uk/news/article/django-cheat-sheet/">Django</a></li>
<li><a href="http://www.addedbytes.com/cheat-sheets/mysql-cheat-sheet/">MySQL</a></li>
<li><a href="http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/">Regular Expressions</a></li>
<li><a href="http://refcards.com/docs/forda/apache/apache-refcard-a4.pdf">Apache</a></li>
<li><a href="http://www.addedbytes.com/apache/mod_rewrite-cheat-sheet/">Mod Rewrite</a></li>
</ul>
<h4>Version Control</h4>
<ul>
<li><a href="http://www.addedbytes.com/cheat-sheets/subversion-cheat-sheet/">SVN (Subversion)</a></li>
<li><a href="http://zrusin.blogspot.com/2007/09/git-cheat-sheet.html">Git</a></li>
</ul>
<h4>Front End Development</h4>
<ul>
<li><a href="http://suda.co.uk/projects/microformats/cheatsheet/">Microformats</a></li>
<li><a href="http://www.cheat-sheets.org/saved-copy/Jquery-Cheat-Sheet-1.2.pdf">jQuery</a></li>
<li><a href="http://www.addedbytes.com/cheat-sheets/html-character-entities-cheat-sheet/">HTML Character Entities</a></li>
</ul>
<h4>Command Line</h4>
<ul>
<li><a href="http://fosswire.com/post/2007/08/unixlinux-command-cheat-sheet/">Unix/Linix Command Line</a></li>
<li><a href="http://www.sans.org/resources/sec560/windows_command_line_sheet_v1.pdf">Windows Command Line</a></li>
</ul>
<h4>Blogging Tools</h4>
<ul>
<li><a href="http://expressionengine.com/docs/quick_reference.html">Expression Engine</a></li>
</ul>
<h4>GMail</h4>
<ul>
<li><a href="http://r.evhead.com/hodgepodge/gmail-shortcuts.html">GMail Shortcuts</a></li>
</ul>
<p>There&#8217;s a comprehensive list available on <a href="http://www.cheat-sheets.org/">cheat-sheets.org</a> and <a href="http://www.addedbytes.com/">Dave Child</a> deserves a lot of credit for his own selection, many of which are linked above.</p>
<p>If you know of any more please link them up in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/17-awesome-web-developer-cheat-sheets/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
		</item>
		<item>
		<title>Tip for Streamlining Your PHP if(statements)</title>
		<link>http://thinkvitamin.com/code/tip-for-streamlining-your-php-ifstatements/</link>
		<comments>http://thinkvitamin.com/code/tip-for-streamlining-your-php-ifstatements/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 14:01:23 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=2608</guid>
		<description><![CDATA[Recently I have been working on a WordPress plugin for Think Vitamin which necessitated getting back into the swing of PHP. Whilst getting my head around how to create the plugin I started to delve into some of the core WordPress files and came across an unfamiliar yet syntactically sweet PHP control structure. It&#8217;s a [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I have been working on a WordPress plugin for Think Vitamin which necessitated getting back into the swing of PHP.</p>
<p>Whilst getting my head around how to create the plugin I started to delve into some of the core WordPress files and came across an unfamiliar yet syntactically sweet PHP control structure. It&#8217;s a simple if statement used in a file that combines PHP and HTML.</p>
<p><span id="more-2608"></span></p>
<p><strong>Old version:</strong></p>
<p><code>&lt;?php if(&lt;your evaluation here&gt;) { ?&gt;<br />
// Output<br />
&lt;?php } else { ?&gt;<br />
// Output<br />
&lt;?php }; ?&gt;</code></p>
<p><strong>New version: Much easier to read</strong></p>
<p><code>&lt;?php if(&lt;your evaluation here&gt;): ?&gt;<br />
// Output<br />
&lt;?php else: ?&gt;<br />
// Output<br />
&lt;?php endif; ?&gt;</code></p>
<p>It also works on &#8220;for&#8221; and &#8220;while&#8221; loops as well as &#8220;elseif&#8221;.</p>
<p>I have never been a fan of combining HTML and PHP, preferring the separation of code and HTML offered by template engines like Smarty, but I could be persuaded. To me this is syntactically much clearer and in my opinion wouldn&#8217;t be too difficult for non &#8220;coders&#8221; working on your project to grasp.</p>
<p>Here are two further examples from WordPress:</p>
<p><code>&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt;</code></p>
<p><code>&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt;<br />
// Output<br />
&lt;?php endwhile; else: ?&gt;<br />
// Output<br />
&lt;?php endif; ?&gt;</code></p>
<p>There are always new things to learn and learning from other people&#8217;s code is a great place to start.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/tip-for-streamlining-your-php-ifstatements/feed/</wfw:commentRss>
		<slash:comments>86</slash:comments>
		</item>
		<item>
		<title>Silverlight for PHP Developers</title>
		<link>http://thinkvitamin.com/code/silverlight-for-php-developers/</link>
		<comments>http://thinkvitamin.com/code/silverlight-for-php-developers/#comments</comments>
		<pubDate>Fri, 13 Mar 2009 08:00:16 +0000</pubDate>
		<dc:creator>Mark Quirk</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=974</guid>
		<description><![CDATA[A Microsoft browser plug-in might seem an odd target for the PHP developer, more used to working with open source platforms such as Linux, Apache and the MySQL database server. However there is much about Microsoft Silverlight that makes it a good match to such technologies. For a start, it is a free download and [...]]]></description>
			<content:encoded><![CDATA[<p>A Microsoft browser plug-in might seem an odd target for the PHP developer, more used to working with open source platforms such as Linux, Apache and the MySQL database server. However there is much about <a href="http://silverlight.net/">Microsoft Silverlight</a> that makes it a good match to such technologies. For a start, it is a free download and there are versions that run not only on Microsoft Windows XP and Vista but also on Intel-based Apple Macs running OS X 10. It is designed to work not only with Microsoft Internet Explorer but with all major Web browsers, and Microsoft is taking particular care to ensure compatibility with Firefox and Safari. There is even a version for Linux called Moonlight which is being developed as part of the open source Mono Project.</p>
<p>Silverlight is a powerful tool for creating Internet applications that go considerably beyond the capabilities of standard HTML and CSS. It supports a wide range of visual effects and has more than 30 user interface controls built-in, including not only buttons, list boxes and sliders but also a data grid and a calendar. It can display PNG and JPEG image files, and play back WMV, WMA and MP3 media with support for 720p HDTV display modes. Silverlight 1.0 was released in April 2007. The current version is Silverlight 2.0 (originally referred to as Silverlight 1.1) which is fully compatible with the original while offering many enhancements.</p>
<p><strong>Inside a Silverlight application</strong><br />
You define the application that you want Silverlight to present using XAML (eXtensible Application Markup Language). This is based on the XML specification and was designed by Microsoft for initialising structured values and objects. The following XAML document declares a Canvas object containing a TextBlock, which is a lightweight element for displaying text:</p>
<p><img src="http://img.skitch.com/20090316-xse1yrc13d6e36e36y3u9qeei6.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>The visual elements that make up a Silverlight application need to be placed within a container object, and this provides a reference in which they can be positioned. In our example we are using a Canvas object measuring 300 by 100 pixels as the container and we have set its Background property so that it displays in a light blue color. Into this we have placed a single TextBlock object which will display the traditional ‘Hello World!’ text string in a Verdana font 30 pixels in size and 10 pixels below and to the right of the top-left corner of the Canvas object. Note the dot syntax that we have employed to reference properties of the Canvas object.</p>
<p>Actually displaying a Silverlight application within an HTML page need involve little more than a standard Object tag. At its simplest, the following renders our example within a browser:</p>
<p><img src="http://img.skitch.com/20090316-j3piqiwe4gyqjy6dptm64y64k1.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>Here we have defined a space 300 pixels wide and 100 pixels wide in which to place the Silverlight plug-in, as defined by its MIME type. We have also defined a data attribute for the plug-in. In practice this is usually ignored but it can boost performance with some browsers (and note that the trailing comma is necessary as the attribute takes two parameters, the second having a ‘null’ value in this case). Finally, in the event that the client does not have Silverlight 2.0 installed, the anchor element displays a ‘Get Silverlight’ image from the Microsoft Web site which is linked to the page from which the user can download and install the plug-in.</p>
<p>The Silverlight plug-in takes a number of parameters but in this context the most important is ‘source’ which tells the plug-in where to find the application. In this case we are directing it to the file ‘silverlightapp.xml’. If this was to contain the XAML of our earlier example in simple text form, and both these files were uploaded to a directory on your Web server, then opening the HTML page would result in our ‘Hello World!’ application appearing to the top-left of your browser.</p>
<p>The XAML that defines the Silverlight application need not reside in a separate file. It can instead be defined within the page that instantiates the plug-in using a special script block. For example, we could insert the following immediately before the ‘pluginHost’ div block in our HTML page above, which also shows off some of the special effects supported by Silverlight:</p>
<p><img src="http://img.skitch.com/20090316-1d6e137qymm1th7b2d3h234m6n.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>We reference this XAML block by changing the ‘source’ parameter for the Silverlight1 object as follows:</p>
<p><img src="http://img.skitch.com/20090316-btpmx13k73gxmk79g7tfrmsiep.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>The hash character indicates that what follows references a script block on the current page. The other principle difference between this and our earlier XAML example is that we have placed a Rectangle object on the Canvas. This is a Shape element, as is the Line, Ellipse, Polygon and Polyline, and as such supports a wider range of display options. The RadiusX and RadiusY attributes round the corners of the Rectangle, while the Fill property allows us to specify a Brush object. In this case we have used the LinearGradientBrush to shade the Rectangle in a graduated blend of yellow and light blue.</p>
<p>Most of the other parameters supported by the Silverlight plug-in can be ignored at this stage. However ‘minRuntimeVersion’ can be useful if you want to ensure, for example, that version 2.0 is installed rather than version 1.0. This can be accompanied by ‘autoUpgrade’ which means that an attempt should be made to upgrade automatically in the event of too early a version being found. There is also the ‘OnLoad’ parameter which can specify a JavaScript function that should be run once the plug-in is loaded (more on that later).</p>
<p>If you want to know more about the options available when instantiating Silverlight, then the article ‘Instantiating a Silverlight Plug-in’ from Microsoft’s MSDN Library is a good place to start.</p>
<p><strong>Using PHP with Silverlight</strong><br />
For the PHP developer, the important point is that the source for the Silverlight object can be anything that returns XAML, and that includes a PHP script. This opens up many possibilities. For example, the following PHP page uses Silverlight to display data extracted from a MySQL database:</p>
<p><img src="http://img.skitch.com/20090316-cmbi1kr98aatyr7sya9378x2k6.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>Assuming this is part of the page ‘customers.php’ on our PHP server, then calling it with the following URL would cause Silverlight to display the name, city and postcode of the 134th customer in the database:</p>
<p>http://myserver.com/customers.php?ID=134</p>
<p>Having extracted the ID value from the query string, the code opens a connection to the database and then runs a query which gets the data for the customer specified and places it in the object $result. The function mysqli_fetch_array() extracts the data from $result into the array $row, from where it can be read and inserted into the XAML using the echo command.<br />
This is far from production code, with little in the way of error checking, but it does serve to demonstrate how PHP can be used to generate a Silverlight application. For the sake of simplicity our example embeds the XAML within the page that instantiates the Silverlight control, but you could equally specify a PHP page as the source for the Silverlight control itself, as in the following snippet:</p>
<p><img src="http://img.skitch.com/20090316-xmwm5x3pqk67k11mpaty7fibx5.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>All that is required here is that the page clients.php return valid XAML code that can be rendered by Silverlight.</p>
<p><strong>Adding user interaction with JavaScript</strong><br />
The Silverlight plug-in exposes a JavaScript API that allows any XAML element can be manipulated by JavaScript, in much the same way that you would program against the HTML Document Object Model (DOM) exposed by the page. Furthermore, Silverlight boasts a wide range of programmable events which opens up many possibilities for user interaction.</p>
<p>For example, in the following we have added an ‘x:Name’ attribute to the TextBlock element. This allows JavaScript to access and manipulate the element using the findName function. We have also attached an event handler stating that the JavaScript function changeText should be executed if the user depresses the left mouse button while the pointer is over the Canvas element:</p>
<p><img src="http://img.skitch.com/20090316-d4mf3ka6yd56ei2yq41g9rhyub.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>We can now define the changeText function by adding the following to the page that instantiates the Silverlight object:</p>
<p><img src="http://img.skitch.com/20090316-11nsrcpdrh4mdtatje4w2t9964.png" alt="Code example. Click link below to donwload actual text."></p>
<p><a href="http://thinkvitamin.com/wp-content/uploads/2009/01/silverlight-code.zip">Download complete code example</a></p>
<p>This script locates the element we want to manipulate using the findName function, and then sets its Text attribute to change from ‘Hello World!’ to ‘Goodbye!’ when the Canvas is clicked. One important point to note here is that the JavaScript is interpreted by the browser and not by the Silverlight plug-in. The x:Name attribute provides a handle that allows the findName function to reach into Silverlight for objects declared within the XAML code.</p>
<p>You can use these techniques to respond to a wide range of events. The API allows you to respond to simple movements of the mouse, or when the mouse pointer enters or leaves an object. You can respond to the depression of the left mouse button, and when it is released. Most objects respond to key up and key down events as well, and there are facilities for determining the key combination. The TextBox control supports a TextChanged event, while the PasswordBox control supports a PasswordChanged event and the Button control supports a Click event</p>
<p>One of Silverlight’s great strengths is this ability to manipulate anything you declare in your XAML code through a coherent object model. Check out the Silverlight Developer Center in the MSDN Library for a comprehensive reference to the whole API.</p>
<p><strong>Interacting with a PHP Web Service</strong><br />
Most of the techniques discussed so far work with both versions of Silverlight. However Silverlight 2.0 opens up new possibilities for client-side processing as it includes a version of the .NET Framework and the Common Language Runtime (CLR) which allows it to run client-side code written in C#, Visual Basic and many other languages. The code for such programs is compressed into a single ZIP file together with the XAML definition and a manifest (also written in XML). The result is given the file extension XAP and referenced through the plug-in’s source parameter in the same way as we referenced our XAML file in the example above. When the page containing the plug-in is opened by the client, the XAP file is downloaded and unpacked, and then the code is compiled and executed.</p>
<p>This opens up further opportunities for the PHP programmer as such applications can make calls to Web services, and those Web services can be defined in PHP. For such an application to work the service has to be SOAP 1.1 compliant, and you will need to define a clientaccesspolicy.xml file if the service comes from a different domain to the application. This is to prevent cross-site forgery (see the article Making a Service Available Across Domain Boundaries for more on this).</p>
<p>It is also worth noting that Silverlight 2.0 also includes the Dynamic Language Runtime (DLR) which supports IronPython, IronRuby and Managed JScript. These languages are being developed at Microsoft’s open source project hosting site Codeplex. For further details see Silverlight Dynamic Languages SDK.</p>
<p><strong>Choosing the Right Tools</strong><br />
While not a requirement, Microsoft has released a number of tools that would be useful to the PHP developer looking to work with Silverlight. Microsoft Visual Web Developer 2008 Express Edition is a useful Web page designer with full support for CSS, JavaScript and AJAX. It can also be used with Silverlight Tools for Visual Studio 2008 to automate production of much of the infrastructure behind a Silverlight application. Both can be downloaded from the Microsoft Web site free of charge.</p>
<p>Microsoft Expression Blend 2 is a professional graphic design tool that outputs XAML, allowing designers to create attractive user interfaces and to automatically generate the code required by Silverlight for its display. Alternatively increased support from the community means there are a growing number of third party XAML editors out there as well.</p>
<p>Sitting alongside Blend 2 is Microsoft Expression Web 2. Aimed at the professional Web designer, this latest release introducing many features that have been designed specifically for the PHP developer. There are menu options for inserting common PHP snippets, including pre-defined form, URL and session variables, server side includes and other structures. Furthermore, Expression Web 2 will render the page in Design View as though all the code, including server side includes, were in a single file, allowing you to see your code in action without leaving the editor.</p>
<p>Expression Web 2 understands PHP which means it will colour code language constructs intelligently, and there is full support for auto-completion so that you can see what functions and parameters are available to you as you write the code. Expression Web 2 also includes the PHP 5.2.5 runtime which you can use locally as a development server.</p>
<p>So Silverlight has a great deal to offer the PHP developer &#8211; something that Microsoft is clearly recognising with its support for PHP in Expression Web 2. Trial versions of Microsoft’s Expression range are available for download.</p>
<p>[Main image by Pathfinder Linden]</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/silverlight-for-php-developers/feed/</wfw:commentRss>
		<slash:comments>76</slash:comments>
		</item>
		<item>
		<title>Give your web app international appeal with PHP, Part I</title>
		<link>http://thinkvitamin.com/code/give-your-web-app-international-appeal/</link>
		<comments>http://thinkvitamin.com/code/give-your-web-app-international-appeal/#comments</comments>
		<pubDate>Mon, 04 Jun 2007 01:00:32 +0000</pubDate>
		<dc:creator>Steve Ellis</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.thinkvitamin.com/features/webapps/give-your-web-app-international-appeal</guid>
		<description><![CDATA[Building web apps can be a lot of fun &#8211; particularly if people like and use them. If you dig through your stats the chances are that people from all over the world are visiting you and they speak lots of different languages. By only serving your app or website in English you&#8217;re assuming that [...]]]></description>
			<content:encoded><![CDATA[<p>Building web apps can be a lot of fun &#8211; particularly if people like and use them. If you dig through your stats the chances are that people from all over the world are visiting you and they speak lots of different  languages. By only serving your app or website in English you&#8217;re assuming that everyone can speak it, or at least understand it well enough to get by. Just as learning to speak a new language can open the door to new cultures and ways of thinking, having a website that speaks multiple languages allows you to engage people who might otherwise have left looking for an alternative.</p>
<p>This was the situation we found ourselves in back in March just after we launched <a href="http://www.diarised.com">Diarised</a>. We had people not only visiting us from all over the world but blogging about us in many different languages. We thought it would be a nice idea to get Diarised working in a few.</p>
<p>The process of getting your website ready for multiple languages is known as internationalisation. Internationalisation goes beyond getting the website working in other languages and covers aspects such as dates, times and currency. In this two part article we&#8217;re going to look at how you go about preparing a website for internationalisation. Then we&#8217;ll look at solutions to some of the real-world problems that can arise, such as dynamic data and plurals.</p>
<h3>Associative Arrays</h3>
<p>As a first stab at internationalisation we might try using associative arrays. We could store our translated text using the English text as the key, like so:</p>
<pre>
<code>
  //set up our language arrays

  $english["welcome to example.com"] = "welcome to example.com";
  $english["have a nice day"] = "have a nice day";

  $spanish["welcome to example.com"] = "Bienvenidos a example.com";
  $spanish["have a nice day"] = "Ten un d&iacute;a bueno";
  ...

  /*
  *  We'll set the locale based on a variable in the query string
  */

  switch($_GET["lang"]){
    case "es":		            //es turns the page into Spanish
      $messages = $spanish;
      break;

    default:			    //everything else defaults back to English
      $messages = $english;
      break;
  }
  ...

  echo $messages["welcome to example.com"]
</code>
</pre>
<p>Adding new languages should then be a case of adding more arrays and updating the switch statement. Perfect! Well not quite. There are a few issues with this approach:</p>
<ol>
<li>Dynamic data. What if you need to insert someone&#8217;s username into a sentence? Breaking the sentence down into lots of little phrases will only make your translator&#8217;s life difficult and will probably lead to inaccurate translations.</li>
<li>You&#8217;re assuming your translator will be able to understand PHP array syntax and avoid breaking everything. What happens when they decide to stick something in quotation marks? The last thing you want to do after receiving a translation is to start debugging syntax errors.</li>
<li>This approach won&#8217;t fail gracefully. What happens if you accidentally type: <code>echo $messages["wlcome to example.com"]</code> By missing off the &#8220;e&#8221; your translation will break and leave blank text.</li>
</ol>
<p>Clearly this method has issues. What we really want is a way to allow non-techies to translate our text for us and a way for us to simply &#8220;plug&#8221; the translation back into the website.</p>
<h3>Introducing Gettext</h3>
<p>After ruling out associative arrays to do Diarised translation&#8217;s we decided to use <a href="http://www.gnu.org/software/gettext/">gettext</a>. gettext is the GNU internationalization library and it provides an excellent way of separating code from content. If you&#8217;re hosting on Linux there&#8217;s a good chance it will already be installed on your server.</p>
<h4>So, how does it work?</h4>
<p>The official Gettext website gives a highly detailed and fairly confusing <a href="http://www.gnu.org/software/gettext/manual/gettext.html#Overview">overview</a> but the gist is:</p>
<ol>
<li>You pass every piece of text you need translated through a function called gettext</li>
<li>Once everything has been marked up you run the xgettext command to create a PO (Portable Object) file. This is a plain text file containing the source text and a place for the translated text</li>
<li>You send this to your translator to open with a PO editor</li>
<li>Once your translator has filled out the translations they send the PO file back to you</li>
<li>You compile the PO file into a MO (Machine Object) file that gettext can read</li>
<li>You set the locale of your site to a language (usually through the query string) and sit back and admire your website in a totally different language</li>
</ol>
<p>Step 1 is just a case of the following:</p>
<pre>
<code>
  &lt;p&gt;welcome to example.com&lt;/p&gt;
</code>
</pre>
<p>becomes</p>
<pre>
<code>
  &lt;p&gt;&lt;? echo gettext("welcome to example.com"); ?&gt;&lt;/p&gt;
</code>
</pre>
<p>Marking up your code to use gettext is probably the most irritating step but fortunately you only have to do this once. It will then work for as many languages as you like. The next stage is to get this information into our translation file.</p>
<h3>How to create a PO file</h3>
<p>The first step is to set up the directory structure:</p>
<ol>
<li>In your webroot folder create a folder called locale</li>
<li>Inside that create a folder for each language you plan on supporting and use the language code as the folder name, e.g. for Spanish use es_ES or if you wanted say a localised Argentine version you could have es_AR</li>
<li>Inside each of those folders create a new one called LC_MESSAGES. This is where we will keep our translation files</li>
</ol>
<p>To create the PO file you&#8217;ll need to use the command line but don&#8217;t worry we&#8217;re here to hold your hand. Fire up a terminal window, connect to your webserver and be brave.<br /> The command we need is called xgettext, this will scan a script looking for calls to gettext then grab the text you&#8217;re passing and put it into a PO file. For example:</p>
<pre>
<code>
  # xgettext -o messages.po *.php
</code>
</pre>
<p>This will search every PHP page in the current working directory and stick the results in messages.po.  Once this is done open the file with a plain text editor and make the following change:</p>
<pre>
<code>
  "Content-Type: text/plain; charset=CHARSETn"
</code>
</pre>
<p>becomes</p>
<pre>
<code>
  "Content-Type: text/plain; charset=utf-8n"
</code>
</pre>
<p>Now save it and send it to your translator</p>
<p>Although a PO file is a plain text file its contents aren&#8217;t particularly friendly. Luckily there are a few pieces of software that make editing PO files a bit easier (especially for your translator). For Windows there&#8217;s <a href="http://www.poedit.net/">poedit</a>, and for the Mac there&#8217;s <a href="http://www.triplespin.com/en/products/locfactoryeditor.html">LocFactory Editor</a>. Both are free and will make your translators lives much easier.</p>
<p>When your translator sends the PO file back stick it into the appropriate LC_MESSAGES folder created earlier and open a terminal window so we can compile it</p>
<p>In your command window go to the LC_MESSAGES folder with messages.po and issue the following:</p>
<pre>
<code>
  # msgfmt messages.po
</code>
</pre>
<p>Assuming there were no errors this will churn out a file called messages.mo. This is the compiled file gettext will actually read, any changes to your PO file will require you to redo this step to make the changes live. Now all we need to do is tell gettext which language we want our text in.</p>
<h3>Binding a locale</h3>
<p>This step can be done via a few lines of PHP near the start of your script:</p>
<pre>
<code>
  $locale = $_GET["locale"];

  putenv("LC_ALL=$locale");
  setlocale(LC_ALL, $locale);

  bindtextdomain("messages", "locale/");	//binds the messages domain to the locale folder
  bind_textdomain_codeset("messages","UTF-8"); 	//ensures text returned is utf-8, quite often this is iso-8859-1 by default
  textdomain("messages");	//sets the domain name, this means gettext will be looking for a file called messages.mo
</code>
</pre>
<p><code>$locale</code> will need to be set to the locale that you want the website appear in. To begin with it&#8217;s simplest to set this via the query string as shown above. One of the advantages of gettext is that if it can&#8217;t find a folder for the locale you pick it will just go back to English, meaning when someone sticks locale=kl expecting a Klingon version they&#8217;ll just get English.</p>
<p>That&#8217;s it for part one. At this point you should be able to at least make a start on preparing your websites for internationalisation. In part two we&#8217;re going to look at some of the real world issues you&#8217;re likely to run into and tell you what we did to solve them on Diarised.</p>
<p><script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/give-your-web-app-international-appeal/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 8.805 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-10 02:36:05 -->

