<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:series="http://organizeseries.com/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>PHP Master</title>
	
	<link>http://phpmaster.com</link>
	<description>For PHP Developers | PHP Tutorials | Learn PHP | PHP Script | Security | PHP Date and Forms</description>
	<lastBuildDate>Wed, 19 Jun 2013 14:30:32 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/PHPMaster_feed" /><feedburner:info uri="phpmaster_feed" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Google App Engine and a Plea for Phalcon</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/5Icd4CXNuCY/</link>
		<comments>http://phpmaster.com/google-app-engine-and-a-plea-for-phalcon/#comments</comments>
		<pubDate>Wed, 19 Jun 2013 14:30:32 +0000</pubDate>
		<dc:creator>Bruno Skvorc</dc:creator>
				<category><![CDATA[News & Opinion]]></category>
		<category><![CDATA[Cloud Development]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5966</guid>
		<description><![CDATA[Find out about Google's recent embrace of PHP in Google App Engine, what it means for the PHP community, and how it can be improved even further if they were to add support for the high performing PHP framework Phalcon.]]></description>
				<content:encoded><![CDATA[<p>Let&#8217;s find out about Google&#8217;s recent embrace of PHP in Google App Engine, what it means for the PHP community, and how it can be improved even further if they add support for the high performing PHP framework Phalcon.</p>
<h2>What&#8217;s Google App Engine?</h2>
<p><a href="https://developers.google.com/appengine/" title="Google App Engine - Google Developers" target="_blank">Google App Engine</a> (GAE) is Google&#8217;s cloud computing Platform as a Service offering on which users deploy web applications that live in Google&#8217;s data centers. This means any application we deploy in the environment automatically inherits the stability, interoperability, and scalability of applications such as Gmail, Google+, and more.</p>
<p>While a full discussion of GAE is outside the scope of this article, suffice it to say that GAE is neither a private server nor a virtual private server &#8211; it&#8217;s a platform. As such, it has some limitations. You cannot simply install extensions in it, nor can you write to disk freely. You cannot alter resource limits on your own and you cannot install custom system tools. It isn&#8217;t your average Linux box; it&#8217;s a fully managed colossal environment for enterprise-level applications.</p>
<p>GAE has been steadily rising in popularity over the past few years, especially for deployment of Python 2 and JVM language (Java, Scala, Clojure) applications, but only <a href="https://www.youtube.com/watch?v=Qt1_atU_Qsg" title="Google I/O 2013 - Introducing Google App Engine for PHP - Youtube" target="_blank">recently at Google I/O</a> was it announced that PHP support was added due to <a href="https://code.google.com/p/googleappengine/issues/detail?id=13" title="Issue 13 - googleappengine - PHP language support - Google App Engine - Google Project Hosting" target="_blank">community interest</a>.</p>
<p>GAE deployment is free up to a certain point. If your app exceeds the free usage quotas, you can request a paid upgrade. It&#8217;s a pay-as-you-use model which works best for large scale high-performance applications. As such, optimizing your application and reducing the number of requests is absolutely essential. Not only does it help performance, but it literally saves you money.</p>
<h2>Transitioning to Google App Engine</h2>
<p>GAE&#8217;s filesystem is read-only. The only way to write something to disk (such as file uploads, cache, custom logs, etc.) is to either use an external service like a read-write CDN or use a virtual filesystem like as gae-filestore (more information is available in the Google I/O video linked above and <a href="https://developers.google.com/appengine/docs/python/datastore/#Python_Datastore_API" title="Storing Data - Python Datastore API - Google Developers" target="_blank">here</a>) or <a href="https://developers.google.com/appengine/docs/php/googlestorage/overview" title="Google Cloud Storage PHP API Overview - Google App Engine - Google Developers" target="_blank">Google Cloud Storage</a>. Furthermore, there is no such thing as a local install of MySQL/MariaDB or PostgreSQL. Instead, you have the option of using <a href="https://developers.google.com/cloud-sql/" title="Google Cloud SQL - Google Developers" target="_blank">Google Cloud SQL</a> (which is similar to MySQL but with <a href="https://developers.google.com/cloud-sql/docs/introduction#features" title="About Google Cloud SQL - Google Cloud SQL - Google Developers" target="_blank">limitations</a> and differences we won&#8217;t be covering here).</p>
<p>Needless to say, the PHP developer transitioning to a GAE environment has his work cut out for him. Thankfully the Google PHP team <a href="http://gaeforphp-blog.appspot.com/" title="Tips and Tricks from the Google App Engine PHP team" target="_blank">runs a blog</a> (which is actually a WordPress installation on GAE) with helpful hints and tutorials, and the <a href="https://developers.google.com/appengine/docs/php/" title="PHP Runtime Environment - Google App Engine - Google Developers" target="_blank">documentation</a> for the still experimental PHP implementation is well done. For those interested in a simple overview, there&#8217;s also the quite clear <a href="https://developers.google.com/appengine/docs/php/gettingstarted/introduction" title="Introduction - Google App Engine - Google Developers" target="_blank">Getting Started Guide</a>.</p>
<p>I encourage you to check out all the linked resources to get as acquainted as much as possible with this new environment. GAE&#8217;s endorsement of PHP is a huge shift in the PHP community, and definitely has the potential to impact PHP development in the long run.</p>
<h2>Essential PHP Extensions and Phalcon</h2>
<p>People have already noted the huge downside of not being able to install extensions and have requested the addition of two essential ones: <a href="https://code.google.com/p/googleappengine/issues/detail?id=9342" title="Issue 9342 - googleappengine - PHP mbstring extension - Google App Engine - Google Project Hosting" target="_blank">mbstring</a> and <a href="https://code.google.com/p/googleappengine/issues/detail?id=9340" title="Issue 9340 - googleappengine - ICONV PHP extension support - Google App Engine - Google Project Hosting" target="_blank">iconv</a> (which have since been installed), making GAE&#8217;s PHP runtime that much more usable. Seeing as how PHP support is still experimental and not ready for production, the GAE team is accepting and actively looking over suggestions for new installations and upgrades.</p>
<p>This is where <a href="http://phalconphp.com/" title="Phalcon PHP | High performance PHP framework" target="_blank">Phalcon</a> comes into play. Phalcon is a highly advanced PHP framework written in C and installed as a PHP extension. It offers all of the framework features you&#8217;re used to and much more, but with far greater performance (more speed, fewer resources) and robustness. Written in C, it executes natively and is loaded into memory when your server starts up, essentially enhancing PHP itself with some much needed missing features.</p>
<p>Phalcon is more PHP6 than PHP6 in itself in some ways, and enables you to write fast and secure applications in a fraction of the time it took to build them before. If you haven&#8217;t tried Phalcon out yet, I encourage you to do so &#8211; their <a href="http://docs.phalconphp.com/en/latest/index.html" title="Welcome! - Phalcon 1.1.0 documentation" target="_blank">documentation</a> is very complete and thorough with examples for every API call.</p>
<p>The problem is the aforementioned inability to install custom extensions into GAE&#8217;s PHP, which means Phalcon is permanently unavailable to such environments. Due to Phalcon&#8217;s <a href="http://systemsarchitect.net/performance-benchmark-of-popular-php-frameworks/#post-642" title="Performance Benchmarks of Popular PHP Frameworks | Systems Architect" target="_blank">excellent</a> <a href="http://docs.phalconphp.com/en/latest/reference/benchmark.html" title="Framework Benchmarks | Phalcon 1.1.0 documentation" target="_blank">performance</a>f, it would be a shame if it weren&#8217;t implemented since it would undoubtedly reduce both Google&#8217;s server load and the cost app owners would be faced with. This is why I&#8217;ve <a href="https://code.google.com/p/googleappengine/issues/detail?id=9336" title="Issue 9336 - googleappengine - Install the PhalconFramework PHP extension - Google App Engine - Google Project Hosting" target="_blank">opened a new feature request</a> in GAE&#8217;s issue tracker which you can vote for. So far, it&#8217;s among the top 30 requested features.</p>
<p>Don&#8217;t take my word for it though &#8211; try out Phalcon and see how you like it. Chances are you&#8217;ll be voting for the issue moments later. Please vote exclusively by starring, however &#8211; not by commenting. Comments are there purely for the purpose of helping out with information and potential issues during installation. When a comment is made on Google Code, an email is sent to all people who starred the issue, which might result in some people un-starring if they feel like they&#8217;re being spammed ultimately hurting the effort.</p>
<h2>Summary</h2>
<p>GAE is a brand new opportunity for PHP. It has the potential to revolutionize the world of PHP development and the hosting options available to developers. To be part of this new age from the get-go, stay tuned for PHP-GAE tutorials and Phalcon guides on PHPMaster and follow the situations as they develop via the links in this article, in particular <a href="http://gaeforphp-blog.appspot.com/" title="Tips and Tricks from the Google App Engine PHP team" target="_blank">gaeforphp-blog.appspot.com</a>. And don&#8217;t forget to check out Phalcon and vote for the issue to further the cause, and feel free to shoot me any questions via <a href="http://gplus.to/Swader" title="Bruno Škvorc - Google+" target="_blank">Google+</a> or in the comments below.</p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/5Icd4CXNuCY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/google-app-engine-and-a-plea-for-phalcon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://phpmaster.com/google-app-engine-and-a-plea-for-phalcon/</feedburner:origLink></item>
		<item>
		<title>Data Structures for PHP Devs: Stacks and Queues</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/Tde0_vSOclg/</link>
		<comments>http://phpmaster.com/php-data-structures-1/#comments</comments>
		<pubDate>Mon, 17 Jun 2013 14:30:53 +0000</pubDate>
		<dc:creator>Ignatius Teo</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[PHP Tutorials]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5932</guid>
		<description><![CDATA[A data structure, or abstract data type, is a model that's defined by a collection of operations that can be performed on itself and is limited by the constraints on the effects of those operations. It creates a wall between what can be done to the underlying data and how it is to be done. In this article, you'll learn about two important data structures which have their conceptual origins in everyday usage: the Stack and the Queue.]]></description>
				<content:encoded><![CDATA[<p>A data structure, or <em>abstract data type</em> (ADT), is a model that is defined by a collection of operations that can be performed on itself and is limited by the constraints on the effects of those operations. It creates a wall between what can be done to the underlying data and how it is to be done.</p>
<p>Most of us are familiar with “stacks” and “queues” in normal everyday usage. But, what do supermarket queues and vending machines have to do with data structures? Let&#8217;s find out. In this article, I will introduce you to two basic abstract data types – the Stack and the Queue &#8211; which have their conceptual origins in everyday usage. </p>
<h2>Stacks</h2>
<p>In common usage, a stack is a pile of objects which are typically arranged in layers – for example, a stack of books on your desk, or a stack of trays in the school cafeteria. In computer science parlance, a stack is a sequential collection with a particular property, in that, the last object placed on the stack, will be the first object removed. This property is commonly referred to as <em>last in first out</em>, or <strong>LIFO</strong>. Candy, chip, and cigarette vending machines operate on the same principle; the last item loaded in the rack is dispensed first.</p>
<p>In abstract terms, a stack is a linear list of items in which all additions to  (a “push”) and deletions from (a “pop”) the list are restricted to one end – defined as the “top” (of the stack). The basic operations which define a stack are:</p>
<ul>
<li><strong>init</strong> &#8211; create the stack.</li>
<li><strong>push</strong> &#8211; add an item to the top of the stack.</li>
<li><strong>pop</strong> &#8211; remove the last item added to the top of the stack.</li>
<li><strong>top</strong> &#8211; look at the item on the top of the stack without removing it.</li>
<li><strong>isEmpty</strong> &#8211; return whether the stack contains no more items.</li>
</ul>
<p>A stack can also be implemented to have a maximum capacity. If the stack is full and does not contain enough slots to accept new entities, it is said to be an “overflow”  – hence the phrase “stack overflow”. Likewise, if a pop operation is attempted on an empty stack, a “stack underflow” occurs.</p>
<p>Knowing that our stack is defined by the LIFO property and a number of basic operations, notably “push” and “pop”, we can easily implement a stack using arrays since arrays already provide push and pop operations.</p>
<p>Here&#8217;s what our simple stack looks like:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
class ReadingList
{
    protected $stack;
    protected $limit;
    
    public function __construct($limit = 10) {
        // initialize the stack
        $this-&gt;stack = array();
        // stack can only contain this many items
        $this-&gt;limit = $limit;
    }

    public function push($item) {
        // trap for stack overflow
        if (count($this-&gt;stack) &lt; self::$limit) {
            // prepend item to the start of the array
            array_unshift($this-&gt;stack, $item);
        } else {
            throw new RunTimeException('Stack is full!'); 
        }
    }

    public function pop() {
        if ($this-&gt;isEmpty()) {
            // trap for stack underflow
	      throw new RunTimeException('Stack is empty!');
	  } else {
            // pop item from the start of the array
            return array_shift($this-&gt;stack);
        }
    }

    public function top() {
        return current($this-&gt;stack);
    }

    public function isEmpty() {
        return empty($this-&gt;stack);
    }
}</pre>
<p>In this example, I&#8217;ve used <code>array_unshift()</code> and <code>array_shift()</code>, rather than <code>array_push()</code> and <code>array_pop()</code>, so that the first element of the stack is always the “top”. You could use <code>array_push()</code> and <code>array_pop()</code> to maintain semantic consistency, in which case, the Nth element of the stack becomes the “top”. It makes no difference either way since the whole purpose of an abstract data type is to abstract the manipulation of the data from its actual implementation.</p>
<p>Let&#8217;s add some items to the stack:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$myBooks = new ReadingList();
$myBooks-&gt;push('A Dream of Spring');
$myBooks-&gt;push('The Winds of Winter');
$myBooks-&gt;push('A Dance with Dragons');
$myBooks-&gt;push('A Feast for Crows');
$myBooks-&gt;push('A Storm of Swords'); 
$myBooks-&gt;push('A Clash of Kings');
$myBooks-&gt;push('A Game of Thrones');</pre>
<p>To remove some items from the stack:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo $myBooks-&gt;pop(); // outputs 'A Game of Thrones'
echo $myBooks-&gt;pop(); // outputs 'A Clash of Kings'
echo $myBooks-&gt;pop(); // outputs 'A Storm of Swords'</pre>
<p>Let&#8217;s see what&#8217;s at the top of the stack:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo $myBooks-&gt;top(); // outputs 'A Feast for Crows'</pre>
<p>What if we remove it?</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo $myBooks-&gt;pop(); // outputs 'A Feast for Crows'</pre>
<p>And if we add a new item?</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$myBooks-&gt;push('The Armageddon Rag');
echo $myBooks-&gt;pop(); // outputs 'The Armageddon Rag'</pre>
<p>You can see the stack operates on a last in first out basis. Whatever is last added to the stack is the first to be removed. If you continue to pop items until the stack is empty, you&#8217;ll get a stack underflow runtime exception.</p>
<pre>PHP Fatal error:  Uncaught exception 'RuntimeException' with message 'Stack is empty!' in /home/ignatius/Data Structures/code/array_stack.php:33
Stack trace:
#0 /home/ignatius/Data Structures/code/example.php(31): ReadingList->pop()
#1 /home/ignatius/Data Structures/code/array_stack.php(54): include('/home/ignatius/...')
#2 {main}
  thrown in /home/ignatius/Data Structures/code/array_stack.php on line 33</pre>
<p>Oh, hello&#8230; PHP has kindly provided a stack trace showing the program execution call stack prior and up to the exception!</p>
<h2>The SPLStack</h2>
<p>The SPL extension provides a set of standard data structures, including the SplStack class (PHP5 &gt;= 5.3.0).  We can implement the same object, although much more tersely, using an SplStack as follows:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
class ReadingList extends SplStack {}</pre>
<p>The <code>SplStack</code> class implements a few more methods than we&#8217;ve originally defined. This is because <code>SplStack</code> is implemented as a doubly linked list, which provides the capacity to implement a traversable stack.</p>
<p>A linked list, which is another abstract data type itself, is a linear collection of objects (nodes) used to represent a particular sequence, where each node in the collection maintains a pointer to the next node in collection. In its simplest form, a linked list looks something like this:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/dstructure1-01.png" alt="dstructure1-01" width="408" height="41" class="aligncenter size-full wp-image-5933" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<p>In a doubly linked list, each node has two pointers, each pointing to the next and previous nodes in the collection. This type of data structure allows for traversal in both directions.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/dstructure1-02.png" alt="dstructure1-02" width="500" class="aligncenter size-full wp-image-5934" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<p>Nodes marked with a cross (X) denotes a null or sentinel node – which designates the end of the traversal path (i.e. the path terminator).</p>
<p>Since <code>ReadingList</code> is implemented as an <code>SplStack</code>, we can traverse the stack forward (top-down) <em>and</em> backward (bottom-up). The default traversal mode for <code>SplStack</code> is LIFO:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
// top-down traversal
// default traversal mode is SplDoublyLinkedList::IT_MODE_LIFO|SplDoublyLinkedList::IT_MODE_KEEP
foreach ($myBooks as $book) {
  echo &quot;$book\n&quot;; // prints last item first!
}</pre>
<p>To traverse the stack in reverse order, we simply set the iterator mode to FIFO (first in, first out):</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
// bottom-up traversal
$myBooks-&gt;setIteratorMode(
    SplDoublyLinkedList::IT_MODE_FIFO|SplDoublyLinkedList::IT_MODE_KEEP
);
foreach ($myBooks as $book) {
  echo $book . &quot;\n&quot;;  // prints first added item first
}</pre>
<h2>Queues</h2>
<p>If you&#8217;ve ever been in a line at the supermarket checkout, then you&#8217;ll know that the first person in line gets served first. In computer terminology, a queue is another abstract data type, which operates on a <em>first in first out</em> basis, or <strong>FIFO</strong>. Inventory is also managed on a FIFO basis, particularly if such items are of a perishable nature.</p>
<p>The basic operations which define a queue are:</p>
<ul>
<li><strong>init</strong> &#8211; create the queue.</li>
<li><strong>enqueue</strong> &#8211; add an item to the “end” (tail) of the queue.</li>
<li><strong>dequeue</strong> &#8211; remove an item from the “front” (head) of the queue.</li>
<li><strong>isEmpty</strong> &#8211; return whether the queue contains no more items.</li>
</ul>
<p>Since <code>SplQueue</code> is also implemented using a doubly linked list, the semantic meaning of “top” and “pop” are reversed in this context. Let&#8217;s redefine our <code>ReadingList</code> class as a queue:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
class ReadingList extends SplQueue {}[

$myBooks = new ReadingList;

// add some items to the queue
$myBooks-&gt;enqueue('A Game of Thrones');
$myBooks-&gt;enqueue('A Clash of Kings');
$myBooks-&gt;enqueue('A Storm of Swords');</pre>
<p><code>SplDoublyLinkedList</code> also implements the <code>ArrayAccess</code> interface so you can also add items to both <code>SplQueue</code> and <code>SplStack</code> as array elements:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$myBooks[] = 'A Feast of Crows';
$myBooks[] = 'A Dance with Dragons;</pre>
<p>To remove items from the front of the queue:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo $myBooks-&gt;dequeue() . &quot;\n&quot;; // outputs 'A Game of Thrones'
echo $myBooks-&gt;dequeue() . &quot;\n&quot;; // outputs 'A Clash of Kings'</pre>
<p><code>enqueue()</code> is an alias for <code>push()</code>, but note that <code>dequeue()</code> is not an alias for <code>pop()</code>; <code>pop()</code> has a different meaning and function in the context of a queue. If we had used <code>pop()</code> here, it would remove the item from the end (tail) of the queue which violates the FIFO rule.</p>
<p>Similarly, to see what&#8217;s at the front (head) of the queue, we have to use <code>bottom()</code> instead of <code>top()</code>:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo $myBooks-&gt;bottom() . &quot;\n&quot;; // outputs 'A Storm of Swords'</pre>
<h2>Summary</h2>
<p>In this article, you&#8217;ve seen how the Stack and Queue abstract data types are used in programming. These data structures are abstract, in that they are defined by the operations that can be performed on itself, thereby creating a wall between its implementation and the underlying data. </p>
<p>These structures are also constrained by the effect of such operations: You can only add or remove items from the top of the stack, and you can only remove items from the front of the queue, or add items to the rear of the queue.</p>
<p><small>Image by <a href="http://www.flickr.com/photos/31797858@N00/8631389697/" target="_blank">Alexandre Dulaunoy</a> via Flickr</small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/Tde0_vSOclg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/php-data-structures-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://phpmaster.com/php-data-structures-1/</feedburner:origLink></item>
		<item>
		<title>Modeling Data Relationships in MongoDB</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/FYTeF_b5rYI/</link>
		<comments>http://phpmaster.com/modeling-data-relationships-in-mongodb/#comments</comments>
		<pubDate>Fri, 14 Jun 2013 14:30:31 +0000</pubDate>
		<dc:creator>Ashish Trivedi</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5926</guid>
		<description><![CDATA[It’s important to consider the data needs of your application right from the very start of development. But if your app will be using NoSQL and you come from a RDBMS/SQL background, then you might think looking at data in terms of NoSQL might be difficult. This article will help you by showing you how some of the basic data modeling concepts apply in the realm of NoSQL.]]></description>
				<content:encoded><![CDATA[<p>It’s important to consider the data needs of your application right from the very start of development. But if your app will be using NoSQL and you come from a RDBMS/SQL background, then you might think looking at data in terms of NoSQL might be difficult. This article will help you by showing you how some of the basic data modeling concepts apply in the realm of NoSQL.</p>
<p>I’ll be using MongoDB for our discussion as it is one of the leading open-source NoSQL databases due to its simplicity, performance, scalability, and active user base. Of course the article assumes that you are aware of basic MongoDB concepts (like collections and documents). If not, I suggest you read some of the previous articles here at PHPMaster to get started with MongoDB. </p>
<h2>Understanding Relationships</h2>
<p>Relationships show how your MongoDB documents are related to each other. To understand the different ways in which we can organize our documents, let’s look at the possible relationships.<br />
<H3>1-to-1 Relationship (1:1)</h3>
<p>A 1:1 relationship exists when one object of an entity is related to one and only one object of another entity. For example, one user can have one and only one birth date. So if we have a document which stores user information and another document which stores birth dates, there will be a 1:1 relationship between them. </p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/mongo-model-01.png" alt="mongo-model-01" width="286" height="64" class="aligncenter size-full wp-image-5927"  style="float: none !important; margin-left:auto; margin-right: auto;"></p>
<h3>1-to-Many Relationship (1:N)</h3>
<p>Such relationship exists when one object of an entity can be related to many objects of another entity. For example, there can be 1:N relationship between a user and his contact numbers since it is possible for one user to have more than one number.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/mongo-model-02.png" alt="mongo-model-02" width="327" height="214" class="aligncenter size-full wp-image-5928" style="float: none !important; margin-left:auto; margin-right: auto;"></p>
<h3>Many-to-Many Relationship (M:N)</h3>
<p>Such relationship exists when one object of an entity is related to many objects of another entity and vice versa. If we correlate it to the case of users and items bought by them, one user can purchase more than one items as well as one item can be purchased by more than one user.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/mongo-model-03.png" alt="mongo-model-03" width="527" height="143" class="aligncenter size-full wp-image-5929" style="float: none !important; margin-left:auto; margin-right: auto;"></p>
<h2>Modeling 1-to-1 Relationships (1:1)</h2>
<p>Consider the following example where we need to store address information for each user (for now let’s assume that there’s a single address for each user). In this case, we can design an embedded document having the following structure:</p>
<pre class="brush: jscript; title: ; notranslate">{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d8524270060001f4&quot;),
    &quot;user_name&quot;: &quot;Mark Benzamin&quot; 
    &quot;dob&quot;: &quot;12 Jan 1991&quot;,
    &quot;address&quot;: {
       &quot;flat_name&quot;: &quot;305, Sunrise Park&quot;,
       &quot;street&quot;: &quot;Cold Pool Street&quot;,
       &quot;city&quot;: &quot;Los Angeles&quot; 
    }
}</pre>
<p>We have the <code>address</code> entity embedded within the user entity making all of the information present in a single document. This means we can find and retrieve everything with a single query.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
// query to find user 'Mark Benzamin' and his address 
$cursor = $collection-&gt;find(
    array(&quot;user_name&quot; =&gt; &quot;Mark Benzamin&quot;),
    array(&quot;user_name&quot; =&gt; 1,&quot;address&quot; =&gt; 1)
 );</pre>
<p>Embedding documents is roughly analogous to de-normalization and is useful when there is a “contains” relationship between two entities. That is, one document can be stored within another, thus placing the related pieces of information within a single document. As all the information is available in one document, such approach has better read performance because a query operation within a document is less expensive for the server and we find and retrieve the related data in the same query.</p>
<p>In contrast, a normalized approach would call for two documents (ideally in separate collections), one to store basic user information and another to store address information. The second document would contain a <code>user_id</code> field indicate the user to which the address belongs.</p>
<pre class="brush: jscript; title: ; notranslate">{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d8524270060001f4&quot;),
    &quot;user_name&quot;: &quot;Mark Benzamin&quot;,
    &quot;dob&quot;: &quot;12 Jan 1991&quot;
}</pre>
<pre class="brush: jscript; title: ; notranslate">{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d852427006000de4&quot;),
    &quot;user_id&quot;: ObjectId(&quot;5146bb52d8524270060001f4&quot;), 
    &quot;flat_name&quot;: &quot;305, Sunrise Park&quot;,
    &quot;street&quot;: &quot;Cold Pool Street&quot;,
    &quot;city&quot;: &quot;Los Angeles&quot; 
}</pre>
<p>We now need to execute two queries to fetch the same data: </p>
<pre class="brush: php; title: ; notranslate">&lt;?php
// query to find user information
$user = $collection-&gt;findOne(
    array(&quot;user_name&quot; =&gt; &quot;Mark Benzamin&quot;),
    array(&quot;_id&quot; =&gt; 1, &quot;user_name&quot; =&gt; 1)
);

// query to find address corresponding to user
$address = $collection-&gt;findOne(
    array(&quot;user_id&quot; =&gt; $user[&quot;_id&quot;]),
    array(&quot;flat_name&quot; =&gt; 1, &quot;street&quot; =&gt; 1, &quot;city&quot; =&gt; 1)
);</pre>
<p>The first query fetches the <code>_id</code> of the user which is then used in the second query to retrieve his address information.</p>
<p>The embedding approach makes more sense than the referencing approach in this case since we are frequently retrieving <code>user_name</code> and <code>address</code> together. What approach you should use ultimately depends on how you logically connect your entities and what data you need to retrieve from the database.</p>
<h2>Modeling Embedded 1-to-Many Relationships (1:N)</h2>
<p>Now let’s consider the case where one user can have multiple addresses. If all of the addresses should be retrieved along with the basic user information, it would be ideal to embed the address entities inside the user entity.</p>
<pre class="brush: jscript; title: ; notranslate">{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d8524270060001f4&quot;),
    &quot;user_name&quot;: &quot;Mark Benzamin&quot;
    &quot;address&quot;: [
        {
            &quot;flat_name&quot;: &quot;305, Sunrise Park&quot;,
            &quot;street&quot;: &quot;Cold Pool Street&quot;,
            &quot;city&quot;: &quot;Los Angeles&quot;
        },
        {
            &quot;flat_name&quot;: &quot;703, Sunset Park&quot;,
            &quot;street&quot;: &quot;Hot Fudge Street&quot;,
            &quot;city&quot;: &quot;Chicago&quot; 
        }
    ]
}</pre>
<p>We’re still able to fetch all of the required information with a single query. The referencing/normalized approach would have us design three documents (one user, two addresses) and two queries to accomplish the same task.<br />
Besides efficiency and convenience, we should use the embedded approach in instances where we need atomicity in operations. Since any updates happen within the same document, atomicity is always insured.</p>
<h2>Modeling Referenced 1-to-Many Relationships (1: N)</h2>
<p>Bear in mind that embedded documents can continue to grow in size over the life of an application which can badly impact write performance. There’s also a limit of 16MB on the maximum size of each document. A normalized approach is preferred if the embedded documents would be too large, when the embedding approach would result in a lot of duplicate data, or if you need to model complex or hierarchical relationships between documents.</p>
<p>Consider the example of maintaining posts made by a user. Let’s assume that we want the user’s name and his profile picture with every post (similar to a Facebook post where we can see a name and profile picture with every post). The denormalized approach would store the user information in each post document:</p>
<pre class="brush: jscript; title: ; notranslate">{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d8524270060001f7&quot;),
    &quot;post_text&quot;: &quot;This is my demo post 1&quot;, 
    &quot;post_likes_count&quot;: 12, 
    &quot;user&quot;: {
        &quot;user_name&quot;: &quot;Mark Benzamin&quot;,
        &quot;profile_pic&quot;: &quot;markbenzamin.jpg&quot;
    }
}

{
   &quot;_id&quot;: ObjectId(&quot;5146bb52d8524270060001f8&quot;),
   &quot;post_text&quot;: &quot;This is my demo post 2&quot;, 
   &quot;post_likes_count&quot;: 32, 
    &quot;user&quot;: {
        &quot;user_name&quot;: &quot;Mark Benzamin&quot;,
        &quot;profile_pic&quot;: &quot;markbenzamin.jpg&quot;
    }
}</pre>
<p>We can see this approach stores redundant information in each post document. Looking a bit forward, if the user name or profile picture was ever changed, we would have to update the appropriate field in all of the corresponding posts.<br />
So the ideal approach would be to normalize the information and connect it via references.</p>
<pre class="brush: jscript; title: ; notranslate">{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d852427006000121&quot;),
    &quot;user_name&quot;: &quot;Mark Benzamin&quot;,
    &quot;profile_pic&quot;: &quot;markbenzamin.jpg&quot;
}</pre>
<pre class="brush: jscript; title: ; notranslate">{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d8524270060001f7&quot;),
    &quot;post_text&quot;: &quot;This is my demo post 1&quot;, 
    &quot;post_likes_count&quot;: 12, 
    &quot;user_id&quot;: ObjectId(&quot;5146bb52d852427006000121&quot;)
}

{
    &quot;_id&quot;: ObjectId(&quot;5146bb52d8524270060001f8&quot;),
    &quot;post_text&quot;: &quot;This is my demo post 2&quot;, 
    &quot;post_likes_count&quot;: 32, 
    &quot;user_id&quot;: ObjectId(&quot;5146bb52d852427006000121&quot;)
}</pre>
<p>The <code>user_id</code> field in the post document contains a reference to the user document. Thus, we can fetch posts made by the user using two queries as follows:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$user = $collection-&gt;findOne(
    array(&quot;user_name&quot; =&gt; &quot;Mark Benzamin&quot;),
    array(&quot;_id&quot; =&gt; 1, &quot;user_name&quot; =&gt; 1, &quot;profile_pic&quot; =&gt; 1)
); 

$posts = $collection-&gt;find(
    array(&quot;user_id&quot; =&gt; $user[&quot;_id&quot;])
);</pre>
<h2>Modeling Many-to-Many Relationships (M:N)</h2>
<p>Let’s take our previous example of storing users and the items they purchased (ideally in separate collections) and design referenced documents to illustrate the M:N relationship. Assume the collection which store documents for user information is as follows such that each document contains reference IDs for the list of items purchased by the user.</p>
<pre class="brush: jscript; title: ; notranslate">{                                 
    &quot;_id&quot;: &quot;user1&quot;,
    &quot;items_purchased&quot;: {
        &quot;0&quot;: &quot;item1&quot;,
        &quot;1&quot;: &quot;item2&quot; 
    } 
}

{
    &quot;_id&quot;: &quot;user2&quot;,
    &quot;items_purchased&quot;: {
        &quot;0&quot;: &quot;item2&quot;,
        &quot;1&quot;: &quot;item3&quot; 
    } 
}</pre>
<p>Similarly, assume another collection storing the documents for the available items. These documents will in turn store reference IDs for the list of users who have purchased it.</p>
<pre class="brush: jscript; title: ; notranslate">{                                 
    &quot;_id&quot;: &quot;item1&quot;,
    &quot;purchased_by&quot;: {
        &quot;0&quot;: &quot;user1&quot;
    } 
}

{                                 
    &quot;_id&quot;: &quot;item2&quot;,
    &quot;purchased_by&quot;: {
        &quot;0&quot;: &quot;user1&quot;,
        &quot;1&quot;: &quot;user2&quot; 
    } 
}

{                                 
    &quot;_id&quot;: &quot;item3&quot;,
    &quot;purchased_by&quot;: {
        &quot;0&quot;: &quot;user2&quot;
    } 
}</pre>
<p>To fetch all the items purchased by a user, we would write the following query:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
// query to find items purchased by a user
$items = $collection-&gt;find(
    array(&quot;_id&quot; =&gt; &quot;user1&quot;),
    array(&quot;items_purchased&quot; =&gt; 1)
);</pre>
<p>The above query will return the IDs of all the items purchased by user1. We can later use these to fetch the corresponding item information. </p>
<p>Alternatively, if we wanted to fetch the users who have purchased a specific item, we would write the following:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
// query to find users who have purchased an item
$users = $collection-&gt;find(
    array(&quot;_id&quot; =&gt; &quot;item1&quot;),
    array(&quot;purchased_by&quot; =&gt; 1)
);</pre>
<p>The above query returns the IDs of all the users who have purchased item1. We can later use these IDs to fetch the corresponding user information.</p>
<p>This example demonstrated M:N relationships which are very useful in some cases. However, you should keep in mind that many times such relationships can be handled using 1:N relationships along with some smart queries. This reduces the amount of data to be maintained in both documents.</p>
<h2>Conclusion</h2>
<p>That’s it for this article. We’ve learned about some basic modeling concepts which will surely help you head start your own data modeling: 1-to-1, 1-to-many, and many-to-many relationships, and also a little about data normalization and de-normalization. You should be able to easily apply these concepts to your own application’s modeling needs. If you have any questions or comments related to the article, feel free to share in the comments section below.</p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/FYTeF_b5rYI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/modeling-data-relationships-in-mongodb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://phpmaster.com/modeling-data-relationships-in-mongodb/</feedburner:origLink></item>
		<item>
		<title>Set Up a Webshop with WordPress and WooCommerce</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/wIFz05mYP_w/</link>
		<comments>http://phpmaster.com/set-up-a-webshop-with-wordpress-and-woocommerce/#comments</comments>
		<pubDate>Wed, 12 Jun 2013 14:30:23 +0000</pubDate>
		<dc:creator>Michelle Sanver</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[E-Commerce]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5867</guid>
		<description><![CDATA[Sometimes you need a simple webshop and you want it to just work. Luckily, setting one up is easy with WooCommerce, an eCommerce plugin for WordPress.This article shows you how to setup a simple store with physical and virtual products, tax, and even PayPal support.]]></description>
				<content:encoded><![CDATA[<p>Sometimes you just want a simple webshop. You need it to work and that’s about it. Whether you want to add it to an existing WordPress site or configure it at the same time you set up a WordPress site, it’s all possible with WooCommerce. Let me show you how to setup a simple store with physical and virtual products, tax, and PayPal support without relying on any previous e-commerce or WordPress experience.</p>
<h2>Installing the WordPress E-commerce Plugin</h2>
<p>The first thing you need to do is to install WordPress. Don’t worry; it’s a straight-forward process that’s well documented here: <a href="http://codex.wordpress.org/Installing_WordPress" title="Installing WordPress - WordPress Codex" target="_blank">codex.wordpress.org/Installing_WordPress</a>.</p>
<p>Beyond a WordPress installation (version 3.5+), you’ll also need the following things:</p>
<ul>
<li>fsockopen support (for payment gateway IPN access).</li>
<li>an SSL certificate if you choose to install any direct payment gateways</li>
<li>cURL support (optional) &#8211; some plugins for WooCommerce require cURL.</li>
<li>SOAP support (optional) &#8211; some plugins for WooCommerce require SOAP.</li>
</ul>
<p>Once WordPress is installed, log in to the dashboard with the admin password you chose and familiarize yourself with the menu on the left. The dashboard is an important place where you’ll customize and manage your site to suit your needs.</p>
<p>Next you need to install WooCommerce. There’s two ways you can do this:</p>
<ol>
<li><strong>The automatic installer</strong> &#8211; go to <strong>Plugins -&gt; Add New</strong>, search for “WooCommerce”, and add the plugin. You’ll need to enter your FTP credentials if this is the first time you’re doing this.</li>
<li><strong>Manually</strong> – Download the plugin from <a href="http://wordpress.org/extend/plugins/woocommerce" title="WordPress - WooCommerce - excelling eCommerce - WordPress Plugins" target="_blank">wordpress.org/extend/plugins/woocommerce</a>, unzip the archive, and place the folder in <code>wp-content/plugins</code>.</li>
</ol>
<p>After you have installed WooCommerce, go to <strong>Plugins -&gt; Installed Plugins</strong> and activate the WooCommerce plugin.</p>
<h2>Configuring WooCommerce</h2>
<p>Now that the plugin is activate, click <strong>WooCommerce</strong> in the side menu. Add WooCommerce Pages by pressing the button labeled “Install WooCommerce Pages” in the banner that comes up.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/woo-01.jpg" alt="woo-01" width="600" height="402" class="aligncenter size-full wp-image-5868" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<p>Then press the Settings button on the welcome page to reach the following page: </p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/woo-02.jpg" alt="woo-02" width="600" height="333" class="aligncenter size-full wp-image-5869" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<p>There’s a lot of settings on this page, but let’s focus on the ones you need to make a bookstore with PayPal as your payment provider.</p>
<p><H3>General</h3>
<p>The general settings speak for themselves. The only things I changed for my own setup was the country to Netherlands and the currency to Euros. </p>
<h3>Taxes</h3>
<p>You’ll need to have a little bit of tax knowledge to run a webshop. Under the Tax tab, I clicked the small link at the top that reads “Standard” to enter standard tax rates, and added the Dutch BTW tax (which is 21%). The taxes and their amount vary per location, so be sure to check the rules that apply to you. Because tax rules are different depending on where you are, I can’t provide detailed information beyond this is where you fill in the rates.</p>
<p>If you’re unsure, I recommend calling your local tax office and ask how much you’re allowed to earn and what kind of tax papers you’ll need for your specific store. Setting up a webshop is easy, but dealing with taxes is harder. After all, you don’t want to be accused of committing tax fraud!</p>
<h3>Customers</h3>
<p>To enable customers, go back to the General tab and check the appropriate boxes in the Registration and Customer Accounts sections. For my store, I chose the options below:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/woo-03.jpg" alt="woo-03" width="553" height="158" class="aligncenter size-full wp-image-5870" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<h3>Enabling PayPal</h3>
<p>To enable PayPal integration, go to the Payment Gateways tab and press the small PayPal link at the top. For the sake of this article I’ll show you how to enable the PayPal sandbox since we don’t want to deal with real money in a fake store!</p>
<p>Go to <a href="https://developer.paypal.com/" title="Home | PayPal Developer" target="_blank">developer.paypal.com</a> and login with your existing PayPal account (if you don’t have one, sign up for one). Click the site’s “Applications” menu item and then “Sandbox accounts”. It’s here where you’ll make a new test account.</p>
<p>Create a customer account to test purchases. Fill in the form just as you would a normal account. When it comes to entering a balance, this is all fake money so I like to enter a million here. One can dream&#8230;</p>
<p>Go back to your webshop site again, and in the PayPal link from earlier fill in the e-mail address of your created sandbox account. </p>
<p>If you’re testing locally, payments won’t fully work. They’ll start working once you have the site up and running on an actual domain.</p>
<h2>Customizing your Store</h2>
<p>You now have a fully functional webshop, but it doesn’t really look much like a shop. We need to add some products and select a theme. </p>
<h3>Adding Products</h3>
<p>In the side menu you’ll see a <strong>Products</strong> category. Click it, then select <strong>Add Product</strong> and fill in the information for a new product. This is a pretty straight forward process. </p>
<p>For the sake of example, let’s add a “PHP book” for 20 euros. Let’s also add a “PHP e-book” with a download link (check the “Virtual” and “Downloadable” boxes to make a downloadable product). You can set the product image with the Featured Image feature, and add any additional images using the Product Gallery.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/woo-04.jpg" alt="woo-04" width="600" height="230" class="aligncenter size-full wp-image-5871" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<h3>Adding a Theme</h3>
<p>There are several themes for WooCommerce at <a href="http://www.woothemes.com/product-category/themes/woocommerce/" title="WooCommerce Archives | WooThemese" target="_blank">woothemes.com/product-category/themes/woocommerce</a>, but of course you’re also free to roll your own or customize an existing theme as you please. For the purpose of this article, we want to have the shop up and running as soon as possible, so let’s use <a href="http://www.woothemes.com/products/mystile/" title="Mystile | WordPress themes, plugins and WooCommerce extensions | WooThemes" target="_blank">mystile</a>, a clean free theme. You do however need to register before downloading it. </p>
<p>The process of adding a theme is similar to adding a plugin; to install it manually, add it to <code>wp-content/themes</code> and activate it by going to <strong>Appearance -&gt; Themes</strong> in the side menu and press “Activate” under the theme.</p>
<p>This theme has a selection of settings available in the side menu under <strong>Mystile</strong>, so feel free to try out the different options to make it look and feel the way you want.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/woo-05.jpg" alt="woo-05" width="600" height="452" class="aligncenter size-full wp-image-5872" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<p>If you get a PHP warning in the bottom of the new homepage, it most likely means you need to update your copy of WooFramework. You can do so by going to <strong>Mystile -&gt; Update Framework</strong>.</p>
<h3>Changing the Menu</h3>
<p>We probably don’t need the checkout pages to be available in the site’s menu, so let’s change the menu by going to <strong>Appearance -&gt; Menus</strong> and make a new menu in the Plus sign tab. Name it whatever you want; I chose to name mine “Main menu”. </p>
<p>Then in the Pages box select the pages you want. I added Home:Home, Cart, Shop, My Account, and every subpage under My Account. Be sure that you drag the subpages into position by having them intended under My Account. Once the menu is saved, select it under the “Theme Locations primary menu” dropdown.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/woo-06.jpg" alt="woo-06" width="600" height="332" class="aligncenter size-full wp-image-5873" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<h3>Extra Cleanup</h3>
<p>Remove the sample page by going to <strong>Pages -&gt; All Pages</strong> in the side menu and remove it from there. You may also want to remove the visible sidebar from some of the pages. You can do this by clicking the page’s Quick Edit link and setting its template to “Full Width”.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/woo-07.jpg" alt="woo-07" width="600" height="183" class="aligncenter size-full wp-image-5874" style="float: none !important; margin-left: auto; margin-right: auto;"></p>
<p>The URLs don’t look very nice, either. Instead of something like <em>http://wordpress.dev/?post_type=produc</em>t you might prefer to have something like <em>http://wordpress.dev/products</em>. Go to <strong>Settings -gt; Permalinks</strong> and under the Common Settings section choose “Post name”.</p>
<p> You may also want to change the permalinks for the specific products. Under the Product permalink base section I chose “Shop base with category” to get a nice, sharable link. </p>
<h2>Conclusion</h2>
<p>Congratulations, you’ve successfully created a webshop. If you didn’t run into any problems, this process probably took you less than an hour, maybe two hours with reading this article. That’s how easy it is to get up and running with WordPress and WooCommerce!</p>
<p>WooCommerce is an Open Source project, so if you feel like extending it even further, please <a href="https://github.com/woothemes/woocommerce" title="woothemes/woocommerce - GitHub" target="_blank">check them out on GitHub</a>!</p>
<p><small>Image via <a title="Royalty Free Stock Photos at Fotolia.com" href="http://us.fotolia.com/?utm_source=sitepoint&amp;utm_medium=website_link&amp;utm=campaign=sitepoint" target="_blank">Fotolia</a></small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/wIFz05mYP_w" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/set-up-a-webshop-with-wordpress-and-woocommerce/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://phpmaster.com/set-up-a-webshop-with-wordpress-and-woocommerce/</feedburner:origLink></item>
		<item>
		<title>Manage Complexity with the Facade Pattern</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/eh0RDmjVs-U/</link>
		<comments>http://phpmaster.com/manage-complexity-with-the-facade-pattern/#comments</comments>
		<pubDate>Mon, 10 Jun 2013 14:30:20 +0000</pubDate>
		<dc:creator>Rakhitha Nimesh</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5877</guid>
		<description><![CDATA[Design patterns standardize common solutions for the problems we face in developing complex software. One such problem is managing a complex series of actions in a workflow. The Facade pattern helps hide the complexity to expose a clean, neat API. See exactly what Facade is and how it helps us write good code.]]></description>
				<content:encoded><![CDATA[<p>Design patterns are built to standardize solutions for common problems faced in software development. When we develop complex applications, we should allocate sufficient time for planning the design and structure of the app. When we do so, we have the chance to choose appropriate design patterns. But there can be situations where we use a design pattern without even knowing that we’re using one.</p>
<p>Facade is a design pattern used in almost every web application, but often without knowing. The term “design pattern” creates a mental image of something complex and difficult to understand. Even though this can be true sometimes, the Facade pattern is simple to implementation. Let’s see what Facade is and what it does to help us write good code.</p>
<h2>The Process of Borrowing a Book</h2>
<p>Assume that we’re developing an application for a library management system. Borrowing and returning books are obviously the two most important tasks of such systems. But consider a typical implementation of the book borrowing process:</p>
<ul>
<li>A user comes to the library and returns her borrowed books so she can borrow new ones.</li>
<li>The user must pay a fine for overdue books.</li>
<li>The user, or a member of the library staff, searches for a new book.</li>
<li>The availability of the book is verified.</li>
<li>If the steps above are successfully completed, the location of the book must be retrieved.</li>
<li>The user borrows the book.</li>
<li>The status of the book is marked as unavailable in the system.</li>
</ul>
<p>The implementation of each task is contained in separate classes with their own interfaces. The following code illustrates how a system might let the user borrow a book by calling the necessary methods:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
public class User
{
    public function borrowBook() {
        $bookManager = new Book_Manager();
        $bookManager-&gt;returnBooks();

        $bookPayments = new Book_Payments();
        if ($bookPayments-&gt;hasOverdueBooks()) {
            $bookPayments-&gt;payBookFines();
        }

        $bookLibrary = new Book_Library();
        $bookReservations = new Book_Reservations();

        $book = $bookLibrary-&gt;searchBooks();
        $isAvailable = $bookLibrary-&gt;isBookAvailable($book);
        $isReserved = $bookReservations-&gt;isBookReserved($book); 
        if ($isAvailable &amp;&amp; !isReserved) {
            $bookLibrary-&gt;locateBook($book);

            $bookManager-&gt;borrowBook($book);
            $bookLibrary-&gt;updateBookAvailability($book, $status);
        }
    }
}</pre>
<p>You can see the process of borrowing a book is actually a complex process! In this implementation, a user has to interact with four different classes and around ten methods to borrow a book.</p>
<p>Assume that each bit of functionality is implemented as a separate screen in the application; can you imagine the effort required for borrowing three books with this system? And the borrower doesn’t need to know about functionality such as checking reservations and updating the status. We certainly have a problem with our implementation.</p>
<h2>Implementing a Library Facade</h2>
<p>We need to decouple the user from the complex workflow of the library and allow for a simplified interface exposing just the information directly related to a user – a facade. Let’s see the implementation of the library facade.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
class Library_Facade
{
    public function returnBooks() {
        // previous implementation by calling necessary classes
    }

    public function borrowBooks() {
    }

    public function searchBooks() {
    }

    public function reserveBooks() {
    }
}</pre>
<p>The user can borrow books by calling the <code>borrowBook()</code> method of the <code>Library_Facade</code> class as shown in the following example:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
class User
{
    public function borrowBook() {
        $libraryFacade = new Library_Facade();
        $libraryFacade-&gt;borrowBook();
    }
}</pre>
<p>With this facade-based implementation, the user only talks to the <code>Library_Facade</code> class and has no idea how the functionality is implemented beyond it. A user can directly request any feature from the facade and the facade is responsible for handling the complex process and returning the appropriate information. The Facade pattern adheres to the principle of least knowledge in which each unit should have minimal knowledge about the other units.</p>
<p>Even though the low-level functionality is hidden from the user through the facade, the user can still request low-level classes directly when needed. Think about your own projects and where you might find situations where you’ve implemented the Facade pattern without even realizing it.</p>
<h2>Facade Pattern Definition</h2>
<p>Since we’ve identified the process and importance of implementing the Facade pattern, now it’s time to learn the definition of the pattern. The following is extracted from Wikipedia:</p>
<blockquote><p>A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:</p>
<ul>
<li>make a software library easier to use, understand, and test since the facade has convenient methods for common tasks;</li>
<li>make the library more readable, for the same reason;</li>
<li>reduce dependencies of outside code on the inner workings of a library, since most code uses the facade allowing more flexibility in developing a system;</li>
<li>wrap a poorly designed collection of APIs with a single well-designed API.</li>
</blockquote>
<p>Here’s a class diagram of our library example that identifies the components mentioned in the Facade pattern definition.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/06/facade-01.jpg" alt="facade-01" width="600" height="338" class="aligncenter size-full wp-image-5922" style="float:none !important; margin-left: auto; margin-right: auto;"></p>
<h2>Real World Implementations</h2>
<p>In the previous sections we learned the theory behind the Facade pattern using a library system as an example. In the real world, facades can be much more complex than the implementation in our library scenario. Let’s review some implementations of the pattern in the context of real-world applications and libraries.</p>
<h3>Opauth for Open Authentication</h3>
<p>I <a href="http://phpmaster.com/integrating-open-authentication-using-opauth/" title="Integrating Open Authentication using Opauth">recently wrote an article</a> about a popular Open Authentication library called Opauth, and I suggest you read it if you haven’t already. Assume we’ve developed a professional social network site and we want our users to be able to use other popular sites such as Twitter, LinkedIn, and Facebook to authenticate. To complete the authentication process we use existing third-party libraries for accessing the networks’ services. Let’s look at some sample code for with a Twitter library for achieving the desired functionality.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$toauth = new TwitterOAuth('consumer key', 'consumer secret');

$request_token = $toauth-&gt;getRequestToken('http://exmaple.com/twitter_oauth.php');

$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

if ($toauth-&gt;http_code == 200) {
    $url = $toauth-&gt;getAuthorizeURL($request_token['oauth_token']);
    header('Location: '. $url);
}
else {
    // Generate error
}</pre>
<p>As you can see, we call a set of Twitter-specific library methods to implement the desired functionality. A similar approach would be necessary for both LinkedIn and Facebook. The process has already become complex. We’re not developing a Twitter, Facebook, or Linkedin application; we should just validate the credentials and authenticate the user. Our application shouldn&#8217;t be worried about the implementation of each of these services.</p>
<p>We can solve this problem by using the Opauth library as a facade interface. First we need to specify the login URLs of the desired services in a common format to be identified by the Opauth plugin. Consider the following code for implementing the authentication process.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
public function login($stratergy = '') {
    if ($stratergy != '') {
        $this-&gt;opauth_lib-&gt;initialize();
    }
}</pre>
<p>Once the login link is requested, Opauth identifies the requested service from the URL and initializes the library to redirect the user for authentication. Our application now only needs to create the login links and call the initialize method. All of the complex authentication stuff is handled behind-the-scenes using the respective libraries for each service. This can be considered a perfect example for effectively using the Facade pattern.</p>
<h3>WordPress Meta Functions</h3>
<p>WordPress is not one of the most popular frameworks among serious PHP developers considering the quality of its code. But we can easily find a number of successful facade implementations inside the WordPress codebase. Here I’ll take a look at the <code>update_post_meta()</code> function for saving custom data for WordPress posts.</p>
<p>WordPress allows us to create custom fields associated with existing posts. Think of how we save these fields in a usual situation&#8230; we have to implement all the following tasks:</p>
<ul>
<li>Validate the field data</li>
<li>Filter the data for HTML tags, scripts, and SQL injections</li>
<li>Check the existence of the field in database</li>
<li>Save or update the record based on the existence status</li>
</ul>
<p>That’s quite a lot of work to save one single custom field! WordPress hides the complexity of saving these fields by providing a built-in function called <code>update_post_meta()</code> to act as a facade. This permits us to focus on passing the necessary data related to our application; all of the aforementioned tasks are hidden from the user.</p>
<p>Now consider the implementation of <code>update_post_meta()</code> to identify its functionality as a facade:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
    // make sure meta is added to the post, not a revision
    if ($the_post = wp_is_post_revision($post_id))
        $post_id = $the_post;

    return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
}

function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
    // expected_slashed ($meta_key)
    $meta_key = stripslashes($meta_key);
    $passed_value = $meta_value;
    $meta_value = stripslashes_deep($meta_value);
    $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);

    $check = apply_filters(&quot;update_{$meta_type}_metadata&quot;, null, $object_id, $meta_key, $meta_value, $prev_value);
    if (null !== $check)
        return (bool) $check;

    // Compare existing value to new value if no prev value given and the key exists only once.
    if (empty($prev_value)) {
        $old_value = get_metadata($meta_type, $object_id, $meta_key);
        if (count($old_value) == 1) {
            if ($old_value[0] === $meta_value)
                return false;
        }
    }

    $wpdb-&gt;update($table, $data, $where);
}</pre>
<p>Only the necessary code is shown; the complete source code for the <code>update_metadata()</code> function is available in <code>meta.php</code> file inside the <code>wp-includes</code> directory. But you can see all of the validation, filtering, and database updates are implemented here and only the facade interface has knowledge about the details. </p>
<h3>Conclusion</h3>
<p>Facade is one of the most simple and easy to use design patterns in software development. Throughout this article I talked about various implementations of the Facade pattern. Now it’s time to share your experiences in the comments below. Do you know of any library or service that makes use of facades? Feel free to share the practical implementations of the Facade pattern you’ve come across.</p>
<p><small>Image via <a title="Royalty Free Stock Photos at Fotolia.com" href="http://us.fotolia.com/?utm_source=sitepoint&amp;utm_medium=website_link&amp;utm=campaign=sitepoint" target="_blank">Fotolia</a></small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/eh0RDmjVs-U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/manage-complexity-with-the-facade-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://phpmaster.com/manage-complexity-with-the-facade-pattern/</feedburner:origLink></item>
		<item>
		<title>Proc_Open: Communicate with the Outside World</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/t5hNB7lxJss/</link>
		<comments>http://phpmaster.com/proc-open-communicate-with-the-outside-world/#comments</comments>
		<pubDate>Fri, 07 Jun 2013 14:00:15 +0000</pubDate>
		<dc:creator>Timothy Boronczyk</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Language Features]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5847</guid>
		<description><![CDATA[There are many ways to interact with external processes, for example web services, message queuing systems, sockets, temp files, etc. Given the requirements of how and what you need to work with, you might find yourself working with the <code>proc_open()</code> function. It spawns a new command like <code>exec()</code>, but with open file pointers which can be used to send and receive data to achieve interprocess communication (IPC). This article will show you how easy it is to use this powerful function.]]></description>
				<content:encoded><![CDATA[<p>There are many ways we can interact with other applications from PHP and share data; there&#8217;s web services, message queuing systems, sockets, temporary files, <code>exec()</code>, etc. Well, today I&#8217;d like to show you one approach in particular, <code>proc_open()</code>. The function spawns a new command but with open file pointers which can be used to send and receive data to achieve interprocess communication (IPC).</p>
<h2>What&#8217;s a Pipe?</h2>
<p>To understand how <code>proc_open()</code> and the process sends and receives data, you know know what a pipe is. </p>
<p>The <a href="http://en.wikipedia.org/wiki/Unix_philosophy" title="Unix philosophy - Wikipedia, the free encyclopedia" target="_blank">Unix Philosophy</a> lead early developers to write many small programs each with very specific functionality. These programs shared plain text as a common format, and users could “chain them together” for greater functionality. The output from one command become the input for the next. The virtual channels that let the data flow between commands became known as pipes.</p>
<p>If you&#8217;ve ever worked in a Unix shell then there&#8217;s a good chance you&#8217;ve used pipes, perhaps even without realizing it. For example:</p>
<pre>$ <strong>mysql -u dbuser -p test < mydata.sql</strong></pre>
<p>Here the <code>mysql</code> utility is invoked and a pipe is set up by the system through which the contents of the <code>mydata.sql</code> file is fed into <code>mysql</code> as if you were typing directly at it&#8217;s prompt from your keyboard.</p>
<p>There are two types of pipes: <a href="http://en.wikipedia.org/wiki/Anonymous_pipe" title="Anonymous pipe - Wikipedia, the free encyclopedia" target="_blank">anonymous</a> and <a href="http://en.wikipedia.org/wiki/Named_pipe" title="Named pipe - Wikipedia, the free encyclopedia" target="_blank">named</a>. An anonymous pipe is <em>ad hoc</em>, created only for as long as the process is running and is destroyed once it is no longer needed. The example with redirecting the file contents into <code>mysql</code> above uses an anonymous pipe. A named pipe on the other hand is given a name and can last indefinitely. It&#8217;s created using special commands and often appears as a special file in the filesystem. </p>
<p>Regardless of the type, an important property of any pipe is that it&#8217;s a <a href="http://en.wikipedia.org/wiki/FIFO" title="FIFO - Wikipedia, the free encyclopedia" target="_blank">FIFO</a> (first in, first out) structure. This means the data written into a pipe first by one process is the first data read out from the pipe by the other process.</p>
<h2>Introducing proc_open()</h2>
<p>The PHP function <code>proc_open()</code> executes a command, much like <code>exec()</code> does, but with the added ability to direct input and output streams through pipes. It accepts some optional arguments, but the mandatory arguments are:</p>
<ul>
<li>a command to execute.</li>
<li>an array that describes the pipes to be used.</li>
<li>an array reference that will later be populated with references to the pipes&#8217; endpoints so you can send/receive data.</li>
</ul>
<p>The optional arguments are used for tweaking the execution environment in which the command spawns. I won&#8217;t discuss it here, but you can find <a href="http://php.net/proc_open" title="PHP: proc_open - Manual" target="_blank">more information</a> in the PHP manual.</p>
<p>Aside from the command to execute, I would say the descriptor array that defines the pipes is the most important argument to pay attention to. The documentation explains it as an “indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process,” but what exactly does that mean?</p>
<p>The three main data streams for a well-behaved unix process are STDIN (standard input), STDOUT (standard output), and STDERR (standard error). That is, there&#8217;s a stream for incoming data, one for outgoing data, and a second outgoing stream for informational messages. STDIN has traditionally been represented by the integer 0, STDOUT by 1, and STDERR by 2. So, the definition with key 0 will be used to set up the input stream, 1 for the output stream, and 2 for the error stream.</p>
<p>These definitions themselves can take one of two forms, either an open file resource or an array that describes the nature of the pipe. For an anonymous pipe, the first element of the descriptive array is the string “pipe” and the second is “r”, “w”, or “a” depending if the pipe is to be read from, written to, or appended. For named pipes, the descriptive array holds the string “file”, the filename, and then “r”, “w”, or “a”.</p>
<p>Once called, <code>proc_open()</code> fills the third parameter&#8217;s array reference to return the resources to the process. The elements in the reference can be treated as normal file descriptors and they work with file and stream functions like <code>fwrite()</code>, <code>fread()</code>, <code>stream_get_contents()</code>, etc.</p>
<p>When you&#8217;re done interacting with the external command, it&#8217;s important to clean up after yourself. You can close the pipes (with <code>fclose()</code>) and the process resource (with <code>proc_close()</code>). </p>
<p>Depending on how your target command/process behaves, you may need to close the STDIN connection before it begins its work (so it knows not to expect any more input). And, you should close the STDOUT and STDERR connections before closing the process, or it might hang while it waits for everything to be clean before shutting down.</p>
<h2>A Practical Example: Converting Wiki Markup</h2>
<p>So far I&#8217;ve only talked about how things work, but I haven&#8217;t shown you an example using <code>proc_open()</code> to spawn and communicate with an external process yet. So, let&#8217;s see how easy it is to use.</p>
<p>Suppose we have a need to convert a chunk of text with wiki markup to HTML for display in a user&#8217;s browser. We&#8217;re using the <a href="http://nyctergatis.com/creole/" title="nyctergatis - Nyctergatis Markup Engine" target="_blank">Nyctergatis Markup Engine</a> (NME) to perform the conversion, but since it&#8217;s a compiled C binary we need a way to fire up <code>nme</code> when its needed and a way to pass input and receive output.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
// descriptor array
$desc = array(
    0 =&gt; array('pipe', 'r'), // 0 is STDIN for process
    1 =&gt; array('pipe', 'w'), // 1 is STDOUT for process
    2 =&gt; array('file', '/tmp/error-output.txt', 'a') // 2 is STDERR for process
);

// command to invoke markup engine
$cmd = &quot;nme --strictcreole --autourllink --body --xref&quot;;

// spawn the process
$p = proc_open($cmd, $desc, $pipes);

// send the wiki content as input to the markup engine 
// and then close the input pipe so the engine knows 
// not to expect more input and can start processing
fwrite($pipes[0], $content);
fclose($pipes[0]);

// read the output from the engine
$html = stream_get_contents($pipes[1]);

// all done! Clean up
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($p);</pre>
<p>First the descriptor array is laid out, with 0 (STDIN) as an anonymous pipe that will be readable by the markup engine, 1 (STDOUT) as an anonymous pipe writable by the engine, and 2 (STDERR) redirecting any error messages to an error log file.</p>
<p>The “r” and “w” on the pipe definitions might seem counter intuitive at first, but keep in mind they are the channels that the engine will be using and so are configured from it&#8217;s perspective. We write to the read pipe because the engine will be reading the data from it. We read from the write pipe because the engine has written data to it.</p>
<h2>Conclusion</h2>
<p>There are many ways to interact with external processes; some may be better than using <code>proc_open()</code> given how and what you need to work with, or <code>proc_open()</code> might just be what the doctor ordered for your situation. Of course you&#8217;ll implement what makes sense, but now you&#8217;ll know how to use this powerful function if you need to!</p>
<p>I&#8217;ve placed some example code on the <a href="https://github.com/phpmasterdotcom/CommunicateWithTheOutsideWorld" title="phpmasterdotcom/CommunicateWithTheOutsideWorld - GitHub" target="_blank">PHPMaster GitHub page</a> that simulates a bare-bones wiki using NME, just like in the example above. Feel free to clone it if you&#8217;re interested in playing and exploring further.</p>
<p><small>Image via <a title="Royalty Free Stock Photos at Fotolia.com" href="http://us.fotolia.com/?utm_source=sitepoint&amp;utm_medium=website_link&amp;utm=campaign=sitepoint" target="_blank">Fotolia</a></small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/t5hNB7lxJss" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/proc-open-communicate-with-the-outside-world/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://phpmaster.com/proc-open-communicate-with-the-outside-world/</feedburner:origLink></item>
		<item>
		<title>Understanding Recursion</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/raMoafmPH_0/</link>
		<comments>http://phpmaster.com/understanding-recursion/#comments</comments>
		<pubDate>Wed, 05 Jun 2013 14:30:40 +0000</pubDate>
		<dc:creator>Stefan Froelich</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[PHP Tutorials]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5852</guid>
		<description><![CDATA[Recursion is such that many experienced programmers can go years without using it and many others may never hear of it, which is a shame because it is a truly powerful concept. This article takes a broad look at recursion and how it compares to iteration, and then shows you how to write recursive functions, when to write them, and why you would want to.]]></description>
				<content:encoded><![CDATA[<p>In one of my previous articles <a href="http://phpmaster.com/using-spl-iterators-1/" title="Using SPL Iterators, Part 1">I wrote about iterators</a> and how you can use them. Today I’d like to look at the fraternal twin of iteration: recursion.</p>
<p>Before we talk about recursion, though, let’s take a look at this snippet of code:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function factorial($number) {
    if ($number &lt; 0) {
        throw new InvalidArgumentException('Number cannot be less than zero');
    }
    $factorial = 1;	
    while ($number &gt; 0) {
        $factorial *= $number;
        $number --;
    }
    return $factorial;
}</pre>
<p>A factorial is the result of a number multiplied by all positive integers less than that number, and the function above calculates the factorial of any number given to it using a simple loop. Now let&#8217;s rewrite the example this way:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function factorial_recursive($number) {
    if ($number &lt; 0) {
        throw new InvalidArgumentException('Number cannot be less than zero');
    }
    if ($number == 0) {
        return 1;
    }
    return $number * factorial_recursive($number – 1);
}</pre>
<p>We get the same results when we call both functions, but notice that the second function calculates the factorial by calling itself. This is known as recursion.</p>
<h2>What&#8217;s Recursion?</h2>
<p>A recursive function is one that calls itself, either directly or in a cycle of function calls.</p>
<p>Recursion can also refer to a method of problem solving that first solves a smaller version of the problem and then uses that result plus some other computation to formulate an answer to the original problem. Often times, in the process of solving the smaller version, the method will solve yet a smaller version of the problem, and so on, until it reaches a &#8220;base case&#8221; which is trivial to solve.</p>
<p>To write a recursive function, you need to provide it with some means of return or else it will keep calling itself for eternity (or until the call stack blows up, the script times out, or memory is exhausted). This is known as a guard clause or base case. </p>
<p>The simplest form of a recursive function is as follows:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function my_recursive_func (args) {
    if (simplest case) {
        // The Base Case/Guard Clause that stops the
        // function from running forever
        return simple value;
    }
    else {
        //call function again with simpler args
        my_recursive_func(argsSimplified);
    }
}</pre>
<h2>Types of Recursion</h2>
<p>When a function calls itself directly, it is referred to as direct recursion. A function in a cycle of function calls that eventually invokes itself is called indirect recursion. Look at the example below of indirect recursion:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function A($num) {
    $num -= 1;
    if($num &gt; 0) {	
        echo &quot;A is Calling B($num)\n&quot;;
        $num = B($num);
    }
    return $num;
}

function B($num) {
    $num -= 2;
    if($num &gt; 0) {
        echo &quot;B is Calling A($num)\n&quot;;
        $num = A($num);
    }
    return $num;
}

$num = 4;
echo &quot;Calling A($num)\n&quot;;
echo 'Result: ' . A($num);</pre>
<pre>Calling A(4) 
A is Calling B(3) 
B is Calling A(1) 
Result: 0</pre>
<p>The above example is really useless code just meant to show you how a function can call itself indirectly through another function. Calling either <code>A(n>4)</code> or <code>B(n>4)</code> causes the called function to be called from the other function.</p>
<p>It&#8217;s important to know a function can call itself indirectly like this, but in this article we&#8217;ll only deal with direct recursion.</p>
<h2>A Practical Example</h2>
<p>To show you how powerful recursion can be, we’ll write a function that searches for a key within an array and returns the result.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function find_in_arr($key, $arr) {
    foreach ($arr as $k =&gt; $v) {
        if ($k == $key) {
            return $v;
        }		
        if (is_array($v)) {
            foreach ($v as $_k =&gt; $_v) {
	        if ($_k == $key) {
                    return $_v;
                }
            }
        }
    }
    return false;
}

$arr = [
    'name' =&gt; 'Php Master',
    'subject' =&gt; 'Php',
    'type' =&gt; 'Articles',
    'items' =&gt; [
        'one' =&gt; 'Iteration',
        'two' =&gt; 'Recursion',
        'methods' =&gt; [
            'factorial' =&gt; 'Recursion',
            'fibonacci' =&gt; 'Recursion',
        ],
    ],
    'parent' =&gt; 'Sitepoint',
];

var_dump(
    find_in_arr('two', $arr),
    find_in_arr('parent', $arr),
    find_in_arr('fibonacci', $arr)
);</pre>
<pre>string 'Recursion' (length=9)
string 'Sitepoint' (length=9)
boolean false</pre>
<p>Things are all well and good, but notice that we iterate only two levels deep into the array, and so the search for “Fibonacci” in the third level fails. If we want to search an array of indeterminate depth, this would not suffice. We can instead rewrite the search as a recursive function:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function find_in_arr($key, $arr) {
    foreach ($arr as $k =&gt; $v) {
        if ($k == $key) {
            return $v;
        }
        if (is_array($v)) {
            $result = find_in_arr($key, $v);
            if ($result != false) {
                return $result;
            }
        }
    }	
    return false;
}</pre>
<p>With the recursive function, we can search an array several levels deep since we have not hardcoded how deep the function goes. It just keeps running until it goes over all of the values in the array.</p>
<h2>Head and Tail Recursion</h2>
<p>In all of the examples so far we&#8217;ve been using what is called head recursion. When the function calls itself, it waits for the result from the call before returning a value of its own. It is possible to write functions in such a way that they do not operate on returned values, but instead pass all required values as parameters. This is known as a tail call (or tail recursion). This method is usually preferred as a language&#8217;s runtime can sometimes optimize the calls so that there&#8217;s no danger of blowing up the call stack, but PHP does not do this.</p>
<p>Below is our factorial example modified to make a tail call. Note that the result of the recursive call is returned, instead of manipulated further.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function factorial ($number, $factorial = 1) {
    if ($number &lt; 0) {
        throw new InvalidArgumentException('Number cannot be less than zero (0)');
    }
    if ($number == 0) {
        return $factorial;
    }
    else {
        return factorial($number - 1, $factorial * $number);
    }
}</pre>
<h2>General Advice</h2>
<p>Any code that can be written iteratively can also be written recursively. However, this is not always easy to do (or even wise to do). Recursion shines when traversing trees and lists or performing most O(n log n) sorts. When you need to divide a repetitive problem up, recursion will fit better than an iterative approach, as in the case of searching within the file system and you need to enter any subdirectories to search within as well. Where there&#8217;s the traversal of an indeterminate depth, recursion works great.</p>
<p>Keep in mind that PHP does not optimize recursive functions, even if you write them to make tail calls, and recursive functions in general are less efficient and slower than their iterative counterparts, though they sometimes do the job better as shown in the code samples above. Recursion is usually a favored alternative to iteration in functional programming and therefore most functional languages optimize recursive functions.</p>
<p>If you’re using XDebug,  be sure to inspect your system&#8217;s configuration. By default you’ll have a limit of 100 recursive calls and if you exceed this, your script will throw a “maximum nested limit reached” error. You can update the <code>debug.max_nesting_level</code> config value if you need to change this.</p>
<p>Finally, it’s a good idea to read an <a href="http://joel.inpointform.net/software-development/explanation-of-stack-heap-and-recursion-causing-stack-overflow/" title="The stack, the heap, and recursion leading to stack overflow Joel" target="_blank">explanation of stack heap and recursion causing stack overflow</a> to understand what happens to the call stack during recursion.</p>
<h2>Conclusion</h2>
<p>In this article I&#8217;ve given you a broad look at recursion and how it compares to iteration. I&#8217;ve also show you how to write recursive functions, when to write them, and why. I have also tried warn you of some of the pitfalls that you might fall into when using recursion. </p>
<p>Recursion is such that even many experienced programmers can go years without using it and many others have never even heard of it, which is sad because it is a truly powerful concept. I hope with this article I might have given you sufficient knowledge to go out there and start writing your own recursive functions. But remember that like with fire, you have to always be careful and use the tool wisely.</p>
<p><small>Image by <a href="http://www.flickr.com/photos/24183489@N00/268729905" target="_blank">Alexandre Duret-Lutz</a> via Flickr</small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/raMoafmPH_0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/understanding-recursion/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://phpmaster.com/understanding-recursion/</feedburner:origLink></item>
		<item>
		<title>Aura.Web: Aura’s Page Controller for MVC</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/BNqDbXo0XOs/</link>
		<comments>http://phpmaster.com/aura-web-auras-page-controller-for-mvc/#comments</comments>
		<pubDate>Mon, 03 Jun 2013 14:30:01 +0000</pubDate>
		<dc:creator>Hari K T</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5830</guid>
		<description><![CDATA[Introduce yourself to Aura.Web, the controller component of the Aura Library. This article shows you how to use Aura.Web to build controllers in your MVC-powered application, and also how to use a response transfer object to gather HTTP headers and integrate a template engine for rendering your views.]]></description>
				<content:encoded><![CDATA[<p>MVC is an acronym that means Model-View-Controller. In this tutorial I would like to introduce you to Aura.Web, the controller component of the Aura Library. Here I&#8217;ll show you how to use it to build your own controller, and also how to use a response transfer object to issue HTTP response headers, and integrate a templating engine like Mustache for rendering views.</p>
<h2>Architecture</h2>
<p>The controller is the entry point for a page, and communicates with view and model components. Aura.Web helps us to easily build controllers that follow the Page Controller design pattern.</p>
<p>Each page of an application is usually unique, and Aura.Web provides the <code>Aura\Web\Controller\AbstractPage</code> class that provides the basic functionality that we can extend and use. But in order to create an object that extends the <code>AbstractPage</code> class, we need to provide some dependencies, usually through the constructor. The dependencies are:</p>
<ol>
<li>An instance of an <code>Aura\Web\Context</code> class that represents the environment.</li>
<li>An instance of an <code>Aura\Web\Accept</code> class which helps retrieve Accept headers.</li>
<li>An instance of an <code>Aura\Web\Response</code> which creates a response transfer object.</li>
<li>An implementation of the <code>Aura\Web\SignalInterface</code> which is a signal manager to execute hooks (similar to an observer/event handler).</li>
<li>An implementation of the <code>Aura\Web\Renderer\RendererInterface</code> to incorporate our rendering system.</li>
<li>A parameter array in which we can pass the action methods.</li>
</ol>
<p>The <code>Context</code> class accepts an array of global values, which in most cases will be <code>$GLOBALS</code>. From inside the controller we can use the <code>Context</code> object as <code>$this-&gt;context</code>, and can access <code>$_GET</code>, <code>$_POST</code>, <code>$_FILES</code>, raw <code>php://input</code>, and JSON decoded values using the object&#8217;s methods <code>getQuery()</code>, <code>getPost()</code>, <code>getFiles()</code>, <code>getInput()</code>, and <code>getJsonInput()</code> respectively. We can also check whether the request was made using GET via <code>isGet()</code>, PUT via <code>isPut()</code>, or an Ajax call via <code>isXhr()</code>.</p>
<p>Let&#8217;s assume a request to <em>http://localhost/?name=Hello</em> is made. An example to get the value of the name parameter from within our controller is:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$this-&gt;context-&gt;getQuery('name', 'default value');</pre>
<p>The second parameter to <code>getQuery()</code> is optional; it specifies a default value to be returned if the actual value is empty.</p>
<p>The <code>Accept</code> class accepts an array of <code>$_SERVER</code> information. The reason why it&#8217;s not just hardcoded in the constructor is to give us the flexibility to pass whatever we like for testing and such. The object is also available in our controller using <code>$this-&gt;accept</code>. It&#8217;s methods give us the accepted media type as an array via <code>getContentType()</code>, the character set via <code>getCharset()</code>, encoding via <code>getEncoding()</code>, and language via <code>getLanguage()</code>. A basic example from the action would be:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$this-&gt;accept-&gt;getContentType();</pre>
<p>Note that an array of key/values is returned, similar to:</p>
<pre>Array
(
    &#91;text/html&#93; => 1
    [application/xhtml+xml] => 1
    [application/xml] => 0.9
    [*/*] => 0.8
)</pre>
<p>You may be familiar with using PHP’s <code>header()</code> function to add values to the HTTP response that is sent back to the client. Instead, a <code>Response</code> object is used as a web response transfer object. The object holds the values which we can pass along, and later convert to a proper HTTP response using tools like Aura.Http.</p>
<p>The <code>Response</code> object is also made available in the controller via <code>$this-&gt;getResponse()</code>. The object lets us set the response&#8217;s body content via <code>setContent()</code>, HTTP header values via <code>setHeader()</code>, cookies via <code>setCookie()</code>, and a redirect header via <code>setRedirect()</code>. We can also set the HTTP status code via <code>setStatusCode()</code> and the status text via the <code>setStatusText()</code> methods.</p>
<p>Here’s what extending and using an <code>AbstractPage</code> object looks like:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
namespace Phpmaster\Tutorial\Web\Controller;
use Aura\Web\Controller\AbstractPage;

class Index extends AbstractPage
{
    public function actionGreet() {
        $this-&gt;response-&gt;setContent(
            '&lt;html&gt;' . 
            '&lt;head&gt;&lt;title&gt;Aura web controller&lt;/title&gt;&lt;/head&gt;' .
            '&lt;body&gt;Hello World!&lt;/body&gt;' . 
            '&lt;/html&gt;'
        );
    }
}</pre>
<pre class="brush: php; title: ; notranslate">&lt;?php
use Aura\Web\Context;
use Aura\Web\Accept;
use Aura\Web\Response;
use Aura\Web\Signal;
use Aura\Web\Renderer\None as Renderer;
use Phpmaster\Tutorial\Web\Controller\Index;

$page = new Index(
    new Context($GLOBALS),
    new Accept($_SERVER),
    new Response(),
    new Signal(),
    new Renderer(),
    [
        'action' =&gt; 'greet',
    ]
);
$response = $page-&gt;exec();
echo $response-&gt;getContent();</pre>
<p>The array of parameters passed as the last argument to our extended <code>AbstractPage</code> specifies which actions need to be called, which format needs to be passed to the rendering strategy, and any other parameters for the action method.</p>
<p>In the execution cycle initiated by <code>exec()</code>, the following are invoked:</p>
<ol>
<li><code>pre_exec</code>, a hook which calls the page’s <code>preExec()</code> method.</li>
<li><code>pre_action</code>, a hook calling the <code>preAction()</code> method.</li>
<li><code>action()</code> to find and invoke the action method (it actually creates a Reflection class to retrieve the parameters for the method and then calls it).</li>
<li><code>post_action</code>, a hook calling the <code>postAction()</code> method.</li>
<li><code>pre_render</code>, a hook which calls the <code>preRender()</code> method.</li>
<li><code>render()</code> to render the view.</li>
<li><code>post_render</code>, a hook calling the <code>postRender()</code> method.</li>
<li><code>post_exec</code>, a hook which calls the <code>postExec()</code> method.</li>
</ol>
<h2>Rendering</h2>
<p>In the example above we explicitly set the content in the controller, but this is not really the best way to organize our code. The view should be separated. Aura.Web doesn&#8217;t provide a rendering strategy by default, so it&#8217;s easy to integrate any rendering strategy we like. Here I&#8217;ll use Mustache.</p>
<p>To create a rendering strategy, we need to extend the <code>Aura\Web\Renderer\AbstractRenderer</code> class, in which we define the <code>exec()</code> method. The controller is available to us in the rendering strategy via <code>$this-&gt;controller</code>.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
namespace Phpmaster\Framework\Web\Renderer;
use Aura\Web\Renderer\AbstractRenderer;

class Mustache extends AbstractRenderer
{
    protected $mustache;

    public function __construct($mustache) {
        $this-&gt;mustache = $mustache;
    }

    public function exec() {
        $format = $this-&gt;controller-&gt;getFormat();
        if (! $format) {
            $format = '.html';
        }
        $response = $this-&gt;controller-&gt;getResponse();
        if (!$response-&gt;getContent()) {
            $data    = (array)$this-&gt;controller-&gt;getData();
            $view    = strtolower($this-&gt;controller-&gt;getAction());
            $lastval = basename(
                str_replace('\\', '/', strtolower(
                    get_class($this-&gt;controller)
                ))
            );
            $file =  $lastval . '/' . $view . $format;
            $response-&gt;setContent(
                $this-&gt;mustache-&gt;render($file, $data)
            );
        }
        $response-&gt;setContentType($this-&gt;getContentType($format));
    }

    public function getContentType($format) {
        $mimetypes = [
            '.json' =&gt; 'application/json',
            '.xml'  =&gt; 'application/xml',
            '.html' =&gt; 'text/html',
            '.htm'  =&gt; 'text/html'
        ];
        return array_search($format, $mimetypes);
    }
}</pre>
<p>I’ve made the assumption that we&#8217;re keeping all of the Mustache templates saved using the convention <code><em>&lt;controller name&gt;</em>/<em>&lt;action name&gt;</em>.<em>&lt;format&gt;</em></code>, where the folders mirror <code><em>&lt;controller name&gt;</em></code> and <code><em>&lt;action name&gt;</em>.<em>&lt;format&gt;</em></code> is the template’s filename. For example, a controller class Example with the action hello would find it’s template in <code>example/hello.<em>&lt;format&gt;</em></code>.</p>
<h2>Building HTTP Responses</h2>
<p>We still haven’t built a proper HTTP response, so let&#8217;s see how we can do that now. Once we call the execution cycle of the controller with it’s <code>exec()</code> method we will get back a response transfer object.</p>
<p>The object contains the HTTP status code, status text, cookies, and header values. We can build the HTTP response from it with code similar to that given below:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$response = $page-&gt;exec();

// header('Status: 200 OK');
$statusCode = $response-&gt;getStatusCode();
$statusText = $response-&gt;getStatusText();

$response-&gt;getVersion();
$headers = $response-&gt;getHeaders();
foreach ($headers as $header =&gt; $value) {
    // header('Content-Type: text/html; charset=utf-8');
    header($header . ': ' . $value);
}

$cookies = $response-&gt;getCookies();
foreach ($cookies as $name =&gt; $cookie) {
    setcookie(
        $name,
        $cookie['value'],
        $cookie['expire'],
        $cookie['path'],
        $cookie['domain'],
        $cookie['secure'],
        $cookie['httponly']
    );
}

$contentType = $response-&gt;getContentType();
if (!$contentType) {
    $contentType = 'text/html; charset=utf-8';
}
header('Content-Type: ' . $contentType);
echo $response-&gt;getContent();</pre>
<p>I’ve demonstrated only a pure PHP implementation so it’s easy for everyone to understand, but ideally we would use something like Aura.Http or another library which provides the necessary functionality for us.</p>
<h2>Conclusion</h2>
<p>In this article I’ve covered the basic working principles of Aura.Web, and also showed how we can integrate a rendering strategy and how to build proper HTTP responses. You can use the power of a routing library like Aura.Router <a href="http://phpmaster.com/web-routing-in-php-with-aura-router/" title="Web Routing in PHP with Aura.Router">which I discussed earlier</a> to dynamically call the controller. Maybe in a future article I’ll show how to integrate all of this and build your own framework from Aura components. Stay tuned!</p>
<p><small>Image via <a title="Royalty Free Stock Photos at Fotolia.com" href="http://us.fotolia.com/?utm_source=sitepoint&amp;utm_medium=website_link&amp;utm=campaign=sitepoint" target="_blank">Fotolia</a></small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/BNqDbXo0XOs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/aura-web-auras-page-controller-for-mvc/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://phpmaster.com/aura-web-auras-page-controller-for-mvc/</feedburner:origLink></item>
		<item>
		<title>Extract Objects from an Access Database with PHP, Part 2</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/DJ_sx3rxpDQ/</link>
		<comments>http://phpmaster.com/extract-ole-objects-from-an-access-database-using-php-2/#comments</comments>
		<pubDate>Fri, 31 May 2013 14:30:30 +0000</pubDate>
		<dc:creator>David Francis</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5732</guid>
		<description><![CDATA[The storage of a blob in a database is never a simple matter, and Microsoft's Access database is no exception. Many programmers who need to migrate from legacy Access databases are stumped when confronted with the task of extracting files from OLE Object fields. In this series you'll see how PHP can be used to extract objects from OLE types. This is part 2 and focuses on extracting PDFs and images.]]></description>
				<content:encoded><![CDATA[<p><a href="http://phpmaster.com/extract-ole-objects-from-an-access-database-using-php-1" title="Extract OLE Objects from an Access Database using PHP, Part 1">In the first part of this series</a> we learned how to extract packaged objects from a legacy Access database. In this second part we&#8217;ll learn how to extract Acrobat PDF documents and take a brief look at a selection of image formats.</p>
<p>The only similarity that PDF, GIF, PNG, etc., have when stored in an Access database is that they are all wrapped in an OLE container consisting of a variable length header and trailer. As we shall see, the trailer can be ignored as it was with the package discussed in Part 1. The header is more useful, but doesn&#8217;t contain all the information we need.</p>
<h2>Adobe Acrobat Documents</h2>
<p>In the test database used for this article, there&#8217;s a PDF stored in record number 13:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/ole2-01a.png" alt="ole2-01a" width="304" height="136" class="aligncenter size-full wp-image-5826" style="float: none; margin-left: auto; margin-right: auto;" /></p>
<p>The identification of an Adobe Acrobat Document (PDF) in an Access database OLE object field is achieved using the same method we learned in Part 1 – inspect the first fifty or so bytes looking for a recognisable sequence of characters.</p>
<p>Applying the same method of extracting a chunk of data from the OLE field, then converting it from hexadecimal to decimal, and displaying it in a hex viewer, makes it clear that although we definitely have a PDF stored in the field, we have no other information such as the original name of the PDF or its original file size:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/ole2-02.png" alt="ole2-02" width="600" class="aligncenter size-full wp-image-5735" style="float: none; margin-left: auto; margin-right: auto;" /></p>
<p>Fortunately, there&#8217;s another technique we can use to extract the PDF. Every PDF always starts with the character sequence %PDF and ends with the sequence %%END. This can be verified easily by loading a small PDF in a plain text editor. Alternatively, load one into a hex viewer:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/ole2-03.png" alt="ole2-03" width="600" class="aligncenter size-full wp-image-5736" style="float: none; margin-left: auto; margin-right: auto;" /></p>
<p>Here I&#8217;ve shown only the first and last few bytes, as these are where the PDF delimiters are. The next step is to apply this technique to the contents of the OLE field and find the location of the start and end and of the embedded PDF:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/ole2-04.png" alt="ole2-04" width="600" class="aligncenter size-full wp-image-5737" style="float: none; margin-left: auto; margin-right: auto;" /></p>
<p>Note that it&#8217;s the hexadecimal character sequences that we need to search for; that is, when using PHP&#8217;s <code>strpos()</code> function to find the start of the embedded PDF, look for 25504446. When looking for the end, 2525454F46 is the relevant character sequence.</p>
<p>So what do we have now? We&#8217;ve identified the OLE object as type Acrobat Document, and we have the start and end locations of the embedded file. We thus have all we need to extract the original file from the OLE field using PHP&#8217;s <code>substr()</code> function.</p>
<h2>Other Object Types</h2>
<p>Before discussing popular images types, it&#8217;s worth taking a moment to improve the <code>switch</code> statement presented in Part 1. For the catch-all default condition we simply displayed a message. It&#8217;d be much more useful if any unknown OLE types were extracted and saved to disk for later analysis. The new function <code>extractUnknown()</code> takes the entire contents of the OLE field, converts it from hexadecimal to decimal, then saves it to disk using the record ID as its file name. This allows us to view any unknown OLE type in a hex viewer later to ascertain the type of the embedded object. We&#8217;ll need this in the next section to identify which records have embedded images.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function extractUnknown($id, $data) {
   // convert entire object to decimal and save to disk
   file_put_contents($id . &quot;.txt&quot;, hex2bin($data));
}</pre>
<h2>Popular Image Types</h2>
<p>It&#8217;s not possible to say with any certainty how image types will be identified in an OLE header in any given Access database. It may be that images will be identified as “Paint Shop Pro 6”, or perhaps they&#8217;ll be associated with some other image editing software. It depends entirely on what software was known to the system that was used to store the images and on any file associations that were configured.</p>
<p>In order to know what these unknown types are, we can make a list by running every record with an unknown OLE type through the <code>extractUnknown()</code> function. This will be different across the plethora of legacy Access database that exist today.</p>
<p>The image formats we&#8217;ll consider here are BMP, GIF, JPEG, and PNG.</p>
<h3>GIF, JPEG, PNG</h3>
<p>“Good news, everyone!” These three image types can be processed in exactly the same way. What&#8217;s more, it&#8217;s exactly the same method used earlier to extract an embedded PDF. First we need to find the start position of the embedded image, then the end position, then extract inclusively everything between these two points. The difference is in how we identify the embedded object. The following table summarises these crucial details:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/ole2-05.png" alt="ole2-05" width="426" height="102" class="aligncenter size-full wp-image-5750" style="float: none; margin-left: auto; margin-right: auto;" /></p>
<h3>BMP</h3>
<p>Identifying the delimiters of an embedded BMP is similar, but requires a little more work. Finding the start position is as easy as it is with the file types discussed above, but finding the end position requires a bit of math. Let&#8217;s see the two crucial elements in a hex viewer:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/ole2-06.png" alt="ole2-06" width="600" class="aligncenter size-full wp-image-5738" style="float: none; margin-left: auto; margin-right: auto;" /></p>
<p>The first two bytes (BM in ASCII), underlined in orange, are the start location of the embedded BMP. The following two bytes, underlined in yellow, are the original size of the BMP stored in little-endian format. The size needs to be converted to big-endian format, then multiplied by two because the object is stored in hexadecimal format.</p>
<p>Given that we now have the start position and the size of the embedded object, we can used the same method to extract a BMP as we used in Part 1 to extract an object from a package.</p>
<h2>Putting It All Together</h2>
<p>What follows is the PHP script from Part 1 updated to include the new functionality described above. The basic structure is identical to its previous version, and the additional conditions in the switch() statement shows how easy it is to extend the core logic of the script to accommodate other OLE types.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$offset = array(
    &quot;Packager Shell Object&quot; =&gt; 168,
    &quot;Package&quot; =&gt; 140
);

if (!function_exists(&quot;hex2bin&quot;)) {
    function hex2bin($hexStr) {
        $hexStrLen = strlen($hexStr);
        $binStr = &quot;&quot;;
        $i = 0;
        while ($i &lt; $hexStrLen) {
            $a = substr($hexStr, $i, 2);
            $c = pack(&quot;H*&quot;, $a);
            $binStr .= $c;
            $i += 2;
       }
       return $binStr;
    }
}

$dbName = &quot;db1.mdb&quot;;
$db = new PDO(&quot;odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;&quot;);

$sql = &quot;SELECT * FROM Table1&quot;;
foreach ($db-&gt;query($sql) as $row) {
    $objName = &quot;&quot;;

    switch (getOLEType($row[&quot;image&quot;])) {
        case &quot;Packager Shell Object&quot;:
            list($objName, $objData) = extractPackage($row[&quot;image&quot;], $offset[&quot;Packager Shell Object&quot;]);
            break;
        case &quot;Package&quot;:
            list($objName, $objData) = extractPackage($row[&quot;image&quot;], $offset[&quot;Package&quot;]);
            break;
        case &quot;Acrobat Document&quot;:
            list($objName, $objData) = extractPDF($row[&quot;id&quot;], $row[&quot;image&quot;]);
            break;
        case &quot;Paint Shop Pro 6&quot;:
        case &quot;Bitmap Image&quot;:
            list($objName, $objData) = extractImage($row[&quot;id&quot;], $row[&quot;image&quot;]);
            break;
        default:
            list($objName, $objData) = extractUnknown($row[&quot;id&quot;], $row[&quot;image&quot;]);
    }
    if ($objName != &quot;&quot;) {
        file_put_contents($objName, $objData);
    }
}

function extractUnknown($id, $data) {
    // convert entire object to decimal and save to disk
    file_put_contents($id . &quot;.txt&quot;, hex2bin($data));
}

function extractPackage($data, $offset) {
    // usable header size
    $headerBlock = 500;
   
    // find name
    $tmp = substr($data, $offset, 255);
    $nullPos = findNullPos($tmp);
    $name = substr($tmp, 0, $nullPos);
    $pos = $offset + strlen($name);

    // find data
    // 1st full path
    list($path1, $nameLen) = findFileName($data, $name, $pos, $headerBlock);
    $pos = $path1 + $nameLen;
    // 2nd full path
    list($path2, $nameLen) = findFileName($data, $name, $pos, $headerBlock);
    // check if only one full path
    if ($path2 &gt; $pos) {    
        $pos = $path2 + strlen($name);
    }
    $oleSizePos = $pos + 2;
    $oleObjSize = flipEndian(substr($data, $oleSizePos, 8), 8);
    $oleHeaderEnd = $oleSizePos + 8;
    $objName = hex2bin(substr($tmp, 0, $nullPos)); 

    // extract object
    $objData = getBlob($data, $oleHeaderEnd, hexdec($oleObjSize) * 2);

    return array($objName, $objData);
}

function extractPDF($id, $data) {
    $delimiter = array(
        &quot;pdfStart&quot; =&gt; &quot;25504446&quot;,
        &quot;pdfEnd&quot; =&gt; &quot;2525454F46&quot;
    );
    // %PDF  - start block common to all PDFs
    $offsetStart = strpos($data, $delimiter[&quot;pdfStart&quot;], 0);
    // %%EOF - end block common to all PDFs
    $offsetEnd   = strpos($data, $delimiter[&quot;pdfEnd&quot;], $offsetStart) + 12;
    $objData = getBlob($data, $offsetStart, $offsetEnd - $offsetStart);
    return array($id . &quot;.pdf&quot;, $objData);
}

function extractImage($id, $data) {
    $delimiter = array(
        &quot;bmpStart&quot; =&gt; &quot;424D&quot;,
        &quot;gifStart&quot; =&gt; &quot;4749463839&quot;,
        &quot;gifEnd&quot; =&gt; &quot;003B&quot;,
        &quot;jpgStart&quot; =&gt; &quot;FFD8&quot;,
        &quot;jpgEnd&quot; =&gt; &quot;FFD9&quot;,
        &quot;pngStart&quot; =&gt; &quot;89504E47&quot;,
        &quot;pngEnd&quot; =&gt; &quot;49454E44AE426082&quot;
    );
    $objName = &quot;&quot;;
    if (strpos($data, $delimiter[&quot;bmpStart&quot;], 0) !== false) { // is object a BMP
   	    list($objName, $objData) = extractBMP($id, $data, $delimiter[&quot;bmpStart&quot;]);
    }
    elseif (strpos($data, $delimiter[&quot;gifStart&quot;], 0) !== false) { // is object a GIF89
        list($objName, $objData) = extractGIF($id, $data, $delimiter[&quot;gifStart&quot;], $delimiter[&quot;gifEnd&quot;]);
    }
    elseif (strpos($data, $delimiter[&quot;jpgStart&quot;], 0) !== false) { // is object a JPEG
   	    list($objName, $objData) = extractJPEG($id, $data, $delimiter[&quot;jpgStart&quot;], $delimiter[&quot;jpgEnd&quot;]);
    }
    elseif (strpos($data, $delimiter[&quot;pngStart&quot;], 0) !== false) { // is object a PNG
   	    list($objName, $objData) = extractPNG($id, $data, $delimiter[&quot;pngStart&quot;], $delimiter[&quot;pngEnd&quot;]);
    }
    else {
        // other image types in here
    }
    // save to disk if object was found
    if ($objName != &quot;&quot;) {
        file_put_contents($objName, $objData);
    }
}

function extractBMP($id, $data, $bmpStart) {
    $oleObjStart = strpos($data, $bmpStart, 0);
    $oleObjSize = hexdec( flipEndian(substr($data, $oleObjStart+4, 8), 8) );
    // extract object
    $objData = getBlob($data, $oleObjStart, $oleObjSize * 2);
    return array($id.&quot;.bmp&quot;, $objData);
}

function getBlob($data, $start, $end) {
    return hex2bin(substr($data, $start, $end));
}

function flipEndian($data, $size) {
    $str = &quot;&quot;;
    for ($i = $size - 2; $i &gt;= 0; $i -= 2) {
        $str .= substr($data, $i, 2);
    }
    return $str;
}

function findNullPos($str) {
    // must start on a two-character boundary
    return floor((strpos($str, &quot;00&quot;) + 1) / 2) * 2;
}

function getOLEType($data) {
    // fixed position of OLE type
    $offset = 40;

    $tmp = substr($data, $offset, 255);
    $nullPos = findNullPos($tmp);
    $tmp = substr($tmp, 0, $nullPos);
    $type = hex2bin($tmp);

    return $type;
}

function hexStrToCase($str, $case) {
    $alphabet = 32;
    $tmp = &quot;&quot;;
    $splitHex = array();
    $splitHex = str_split($str, 2);
    $splitTest = hex2bin($splitHex[0]);
    foreach ($splitHex as $key =&gt; $value) {
        switch ($case) {
            case &quot;upper&quot;:
                if ((intval($value, 16) &gt;= ord(&quot;a&quot;)) &amp;&amp; (intval($value, 16) &lt;= ord(&quot;z&quot;))) {
                    $splitHex[$key] = dechex(intval($value, 16) - $alphabet);
                }
                break;
            case &quot;lower&quot;:
                if ((intval($value, 16) &gt;= ord(&quot;A&quot;)) &amp;&amp; (intval($value, 16) &lt;= ord(&quot;Z&quot;))) {
                   $splitHex[$key] = dechex(intval($value, 16) + $alphabet);
                }
                break;
       }
    }
    $tmp = strtoupper(implode($splitHex));
    return $tmp;
}

function hexStrToTilda1($str) {
    $strDot = &quot;2E&quot;;
    $strTilda1 = &quot;7E31&quot;;
    $tmp = hexStrToCase($str, &quot;upper&quot;);
    if (strlen($tmp) &gt; 24) {
        $dotPos = strrpos($tmp, $strDot);
        $tmp = substr($tmp, 0, 12) . $strTilda1 . substr($tmp, $dotPos, 8);
    }
    return $tmp;
}

function findFileName($data, $str, $offset, $headerBlock) {
    $strLen = 0;
    $tmp = substr($data, 0, $headerBlock);
    $strUpper = hexStrToCase($str, &quot;upper&quot;);
    $strLower = hexStrToCase($str, &quot;lower&quot;);
    $strTilda1 = hexStrToTilda1($str);
    $strPos = stripos($tmp, $str, $offset);
    if ($strPos === false) {
        $strPos = stripos($tmp, $strUpper, $offset);
        if ($strPos === false) {
            $strPos = stripos($tmp, $strLower, $offset);
            if ($strPos === false) {
                $strPos = stripos($tmp, $strTilda1, $offset);
                $strLen = strlen($strTilda1);
            }
            else {
                $strLen = strlen($strLower);
            }
        }
        else {
            $strLen = strlen($strUpper);
        }
    }
    else {
        $strLen = strlen($str);
    }
    return array($strPos, $strLen);
}</pre>
<p>You&#8217;ll notice that I&#8217;ve not included code for the functions <code>extractGIF()</code>, <code>extractJPEG()</code>, and <code>extractPNG()</code>. That&#8217;s because I&#8217;m leaving these as an exercise for you, fellow PHP programmers – the code will be very similar to what we&#8217;ve covered for the other OLE object types.</p>
<h2>Summary</h2>
<p>In this article we&#8217;ve covered the essential elements of extracting PDFs from OLE fields in a Microsoft Access database using PHP. We also learned how to identify certain image formats, and how to extract them from their OLE container. </p>
<p>Having completed this two-part introduction to how OLE objects are stored in, and can be retrieved from, a Microsoft Access database, we now have yet another tool to assist us with the migration away from legacy Access databases.</p>
<p>You can get the code for this series on the PHPMaster GitHub page. The repo has two branches &#8211; <a href="https://github.com/phpmasterdotcom/ExtractObjectsFromAccessDatabase/tree/part-1" title="ExtractObjectsFromAccessDatabase at part-1 - GitHub" target="_blank">part-1</a> for code to accompany the first part, and <a href="https://github.com/phpmasterdotcom/ExtractObjectsFromAccessDatabase/tree/part-2" title="ExtractObjectsFromAccessDatabase at part-2 - GitHub" target="_blank">part-2</a> for code for this part. </p>
<p><small>Image via <a title="Royalty Free Stock Photos at Fotolia.com" href="http://us.fotolia.com/?utm_source=sitepoint&amp;utm_medium=website_link&amp;utm=campaign=sitepoint" target="_blank">Fotolia</a></small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/DJ_sx3rxpDQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/extract-ole-objects-from-an-access-database-using-php-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Extract Objects from an Access Database with PHP]]></series:name>
	<feedburner:origLink>http://phpmaster.com/extract-ole-objects-from-an-access-database-using-php-2/</feedburner:origLink></item>
		<item>
		<title>Digital Tickets with PHP and Apple Passbook</title>
		<link>http://feedproxy.google.com/~r/PHPMaster_feed/~3/ji0OTAHaLhk/</link>
		<comments>http://phpmaster.com/create-digital-tickets-with-php-and-apple-passbook/#comments</comments>
		<pubDate>Wed, 29 May 2013 14:30:52 +0000</pubDate>
		<dc:creator>Vito Tardia</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://phpmaster.com/?p=5727</guid>
		<description><![CDATA[Apple's Passbook is a very interesting piece of technology that involves a lot of well-known and loved tools like JSON and RESTful APIs. See how to build a sample web app that creates and distributes passes. Though the example presented isn't a full-featured product, it can serve as a nice base to build on for more serious real world uses. ]]></description>
				<content:encoded><![CDATA[<p>Why should we PHP warriors care at all about Apple’s Passbook? Well first because Apple made this technology open (well, sort of&#8230;), second because it can be used outside iOS devices, and third because it involves a lot of well-known and loved technologies like JSON and RESTful APIs. I&#8217;d also add that it’s a very interesting piece of technology, but that&#8217;s my personal opinion.</p>
<p>In this article I’ll show you how I built a sample web application that creates and distributes passes in the form of a &#8220;PHPMaster Membership Card&#8221;. It is not a full-featured product, but it’s a nice base to build on for more serious real world uses. You can <a href="https://github.com/phpmasterdotcom/CreateDigitalTicketsApplePassbook" title="phpmasterdotcom/CreateDigitalTicketsApplePassbook - GitHub" target="_blank">download the demo code</a> for the article from PHPMaster’s GitHub.</p>
<p><strong>Please note:</strong> In order to run this article’s code, you (or your client) must be registered to one of the paid Apple iOS Developer Programs which allows you to create the necessary certificates to sign your passes. For this reason I’ve also made a dummy application available online for you to play with.</p>
<h2>What&#8217;s a Pass and How do I Use One?</h2>
<p>A pass is a digitally signed document such as a ticket, membership card, or coupon that can be distributed by email or a web download. It can be opened with the Passbook app on iOS or with an app like <a href="https://play.google.com/store/apps/details?id=com.attidomobile.passwallet" title="PassWallet - Passbook + NFC - Android Apps on Google Play" target="_blank">PassWallet</a> on Android. On iOS, a pass can also be linked to a companion app, for example the <a href="https://itunes.apple.com/app/eventbrite/id487922291?mt=8" title="Eventbrite for iPhone, iPod touch, and iPad on the iTunes App Store" target="_blank">Eventbrite</a> app which allows you to buy tickets and add them to your device’s Passbook, but that’s not mandatory.</p>
<p>Apple&#8217;s specs outline four main pass types:</p>
<ul>
<li>Boarding passes</li>
<li>Event tickets</li>
<li>Retail coupons</li>
<li>Store cards</li>
</ul>
<p>There’s also a Generic pass type that covers other purposes, and this the type of pass I&#8217;m using here.</p>
<p>Each pass contains various bits of data. Some, such as a member name and bar code are displayed visually on the &#8220;front side&#8221; of the pass. Other data is located on the &#8220;back&#8221; of the pass and triggered by the &#8220;i&#8221; icon. Passes can also contain some hidden information such as a time and location which can be used to display relevant notifications.</p>
<p>On Apple’s <a href="https://developer.apple.com/passbook/" title="Passbook for Developers - Apple Developer" target="_blank">Passbook Developers page</a> you can find official guides and some sample code.</p>
<h2>App Concept: PHPMaster Membership Card</h2>
<p>The sample application has two main features:</p>
<ul>
<li>Create and store passes</li>
<li>Implement the register/unregister web service API</li>
</ul>
<p><img src="http://cdn.phpmaster.com/files/2013/05/passbook001.png" alt="passbook001" width="600" class="aligncenter size-full wp-image-5840" style="float: none !important; margin-left:auto; margin-right: auto;" /></p>
<p>The main form prompts the user for a full name, an email address, and an optional favorite function. The member picture is fetched using the <a href="http://en.gravatar.com/site/implement/" title="Gravatar - Globally Recognized Avatars" target="_blank">Gravatar API</a>. The backend code then saves the provided data to a database, generates the pass, and sends a copy to the subscriber’s email.</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/passbook002.png" alt="passbook002" width="600" class="aligncenter size-full wp-image-5841" style="float: none !important; margin-left:auto; margin-right: auto;" /></p>
<p>The pass contains the URL and access codes for a web service, so when the subscriber adds the pass to his collection the Passbook app will call a predefined registration URL that must be implemented to check and store the provided data for later use.</p>
<h2>App Structure</h2>
<p>Since the core of this writeup is to understand pass-related code, I&#8217;ll start from a base of well known open source components available on GitHub and using Composer.</p>
<p>The application is built using <a href="http://slimframework.com/" title="Slim Framework" target="_blank">Slim Framework</a> since it’s lightweight and well suited for both RESTful development and web-GUI applications. Slim’s default PHP template engine is used as well the <code>DateTimeLogWriter</code> from the Slim Extras package.</p>
<p>The data and model layer is covered by <a href="http://j4mie.github.io/idiormandparis/" title="Idiorm and paris - object relational mapper (ORM), fluent SQL query builder and Active Record Implmenetation for PHP" target="_blank">Idiorm and Paris</a>. Idiorm takes care of database work, while Paris provides a simple and clean model interface. This allows us to work with a <code>Pass</code> and a <code>Subscriber</code> object and call, for example, <code>$pass-&gt;pack()</code> to generate the pass package.</p>
<h3>Pass Definition</h3>
<p>The first step is to define the pass; how will it look and what data will contain?</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/passbook003.png" alt="passbook003" width="372" height="514" class="aligncenter size-full wp-image-5842" style="float: none !important; margin-left:auto; margin-right: auto;" /></p>
<p>With this information at hand, we can create a pass template directory containing the basic assets:</p>
<pre>templates/passes/PHPMaster.raw/
    logo.png
    icon.png
    pass.json</pre>
<p>Each of the images can have a corresponding <code><em>ImageName</em>@2x.png</code> version that can be used on retina devices if present. The logo is displayed in the top left of the pass, while the icon is displayed in the push notification box and iOS mail app. <code>pass.json</code> contains the data for the pass.</p>
<p>Inside <code>pass.json</code>, <code>teamIdentifier</code> is assigned to us by Apple when we subscribe to the Developer Program. <code>passTypeIdentifier</code> is a unique reverse-domain ID for our pass type, for example <em>pass.com.phpmaster.membership-test</em> (the &#8220;.pass&#8221; prefix is required). The <code>serialNumber</code> field must be unique to each pass, so a good value to use is the primary key from the database table that stores passes.</p>
<p>The <code>generic</code> key indicates the pass type we are using and contains the specific fields for the pass. Each pass type has a set of <code>primaryFields</code>, <code>secondaryFields</code>, and <code>auxiliaryFields</code> displayed in different places on the front side; it can also have a number of <code>backFields</code> displayed on the reverse side. Each field has a label (displayed publicly), a key (for internal reference), and a value.</p>
<p>The <code>webServiceURL</code> and <code>authenticationToken</code> fields are defined later in the application and are filled with the base URL of and the access credentials used by the device to register itself on our server.</p>
<h3>Certificates</h3>
<p>The next step is to obtain the certificate used for pass generation. The Apple Developer’s provisioning panel is used to request certificates and there is a <a href="http://code.google.com/p/passkit/wiki/AppleDeveloperVideo" title="AppleDeveloperVideo - passkit - Enrolling for an Apple Developer Account - Design, create, distribute, manage and analyze Apple Passbook content" target="_blank">nice video tutorial</a> on the PassKit wiki. You need a specific certificate for each pass type; the certificate&#8217;s common name must match the <code>passTypeIdentifier</code> of the pass.</p>
<p>Each pass’s signature must also include the public <a href="https://developer.apple.com/certificationauthority/AppleWWDRCA.cer" title="AppleWWDRCA.cer" target="_blank">Apple WWDR Intermediate Certificate</a>.</p>
<h3>Directory and File Layout</h3>
<p>Here&#8217;s what the layout of the application looks like:</p>
<p><img src="http://cdn.phpmaster.com/files/2013/05/passbook004.png" alt="passbook004" width="214" height="706" class="aligncenter size-full wp-image-5844" style="float: none !important; margin-left:auto; margin-right: auto;" /></p>
<p>The <code>bin</code> directory contains the command line utility <code>signpass.php</code>. This program is a PHP port of Apple’s console utilities written in Objective-C and Ruby. It can be used to validate a pass or to create one from a given directory. It uses the PassSigner library which I detail later.</p>
<p>The <code>config</code> directory holds the configuration files. Make a copy of the sample and name it after your environment (stage, dev, prod, etc). To define a custom environment, create a text file named <code>.mode</code> inside the root directory containing the desired name of your environment. The <code>$config['db']</code> array in the configuration file is used by Idiorm, and the <code>$config['app']</code> array is passed directly to the Slim application’s constructor.</p>
<p>The <code>data</code> directory holds log files, generated passes, the SQL dump file, and the <code>Certificate</code> directory that must contain Apple’s public certificate and the certificate for your pass, both in PEM format. Certificates are distributed in CER or P12 format and can be converted with the openssl utility like so:</p>
<pre>openssl pkcs12 -in data/Certificate/PHPMaster.p12 -out data/Certificate/PHPMaster.pem</pre>
<p>The <code>templates</code> directory holds the front-end template files. There&#8217;s two pages, the home (<code>main.php</code>) and the result page (<code>pass.php</code>), which share the header and footer elements. The subscription form has its own file (<code>form.php</code>).</p>
<p>The <code>passes</code> subdirectory holds templates for each pass type. Each pass&#8217; templates are organized into directories named <code><em>PassTypeOrName</em>.raw</code> containing the necessary files.</p>
<p>The custom library code resides in <code>lib/MyPassbook</code>. Inside this directory there is:</p>
<ul>
<li>the PassSigner library, responsible for pass signing and validation</li>
<li>the model classes built upon the core objects <code>Subscriber</code>, <code>Pass</code>, and <code>Device</code></li>
</ul>
<p><code>DevicePass</code> is an intermediate class needed by Paris and manages the many-to-many relationship between devices and passes; as defined in the Passbook specs, each device can contain many passes and a copy of each pass can be stored in many devices.</p>
<p>The application’s <code>public</code> directory contains the controller files. <code>index.php</code> is the main controller. The controller includes <code>include/bootstrap.php</code> which is responsible for the application’s startup, loading the configuration file, setting up some defaults, connecting ORM to the database, and starting the log writer. In particular, the script also sets some code to the slim.before event hook used to capture the special Authentication HTTP header.</p>
<p>The <code>install.php</code> file is just a quick-and-dirty script that resets the application; there&#8217;s probably no need to say that it must be removed after you&#8217;ve set everything up!</p>
<p>There should also be a <code>.htaccess</code> file that redirects all non-file URIs to <code>index.php</code> and adds a custom mime type for our passes:</p>
<pre>AddType application/vnd.apple.pkpass    pkpass</pre>
<p>This allows Safari to open the pass with the PassViewer utility.</p>
<h2>Writing the Application</h2>
<p>The most important components of the application are the <code>PassSigner</code> class and the <code>index.php</code> front controller. Paris gives us the ability to use model classes so that the underlying database logic is transparent and managed by Idiorm. Creating a model class is as simple as:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
class Subscriber extends Model { }</pre>
<p>There&#8217;s three classes that need to be created: <code>Pass</code>, <code>Device</code>, and <code>Subscriber</code>.</p>
<p>The basic methods such as <code>create()</code>, <code>find_many()</code>, <code>delete()</code>, and so on are inherited from the base class. We can modify the basic properties (for example the linked database table or column ID), enhance the default methods, and add custom methods as needed.</p>
<p>I added three methods to the <code>Subscriber</code> class:</p>
<ul>
<li><code>pass()</code> &#8211; implement a one-to-one relationship with a <code>Pass</code> object and return this object.</li>
<li><code>create()</code> &#8211; override the default <code>create()</code> method allowing an array of data to be passed.</li>
<li><code>createPass()</code> &#8211; create a <code>Pass</code> object linked to the current subscriber.</li>
</ul>
<p>And these are the six methods I added to the <code>Pass</code> class:</p>
<ul>
<li><code>subscriber()</code> &#8211; implement a one-to-one relationship with a <code>Subscriber</code> object and return this object.</li>
<li><code>devices()</code> &#8211; define the many-to-many relationship with the <code>Device</code> object. It has a corresponding <code>passes()</code> method on the <code>Device</code> class.</li>
<li><code>create()</code> &#8211; same as the <code>create()</code> method of the <code>Subscriber</code> class.</li>
<li><code>delete()</code> &#8211; override the default method; delete the linked <code>Devices</code> and <code>Subscriber</code> objects.</li>
<li><code>filename()</code> &#8211; calculate and return the file name for the pass on disk.</li>
<li><code>pack()</code> &#8211; save the pass to disk using the PassSigner library.</li>
</ul>
<h3>The PassSigner library</h3>
<p><code>PassSigner</code> provides two main public methods for pass management:</p>
<ul>
<li><code>signPass()</code> &#8211; take a directory containing data for a single pass and the certificate data and produce a zipped PKPASS file.</li>
<li><code>verifyPassSignature()</code> take a PKPASS file and validate its structure and signature.</li>
</ul>
<p>There are also two utility methods <code>rcopy()</code> and <code>rrmdir()</code> for recursive copy and deletion of directories, and some internal protected methods. The library makes extensive use of exceptions validation functions, and the two important methods check for the Apple certificate which must be defined by the constant <code>APPLE_CERTIFICATE</code> with the certificate path.</p>
<p>To sign a pass, a file named <code>manifest.json</code> must be produced using the pass directory&#8217;s contents. This file must be signed with your certificate and include Apple’s public certificate. The signature data is saved in a file named <code>signature</code>.</p>
<p>Let’s say that we have a directory that contain the pass data:</p>
<pre>data/passes/PassForUser001.raw
    info.png
    logo.png
    thumbnail.png
    pass.json</pre>
<p>The first step is to recursively copy all of the contents to a temporary directory (<code>/tmp/PassForUser001</code> for example). Make sure there&#8217;s no &#8220;junk&#8221; files that shouldn&#8217;t be included, like the annoying <code>.DS_Store</code> files if you&#8217;re on OSX. If any of these files in included in the zipped pass but not in the manifest, the pass is invalid.</p>
<p>Then create the associative array to store the manifest data. There is an item for each file in the pass directory, the relative path is the item’s key while the value is the SHA1 hash of the file. The array is encoded and saved as <code>manifest.json</code> in the pass directory.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$manifestData = array();
$files = new DirectoryIterator($passPath);
foreach ($files as $file) {
    if ($file-&gt;isDot() || $file-&gt;getFilename() == &quot;.DS_Store&quot;) {
        continue;
    }
    $key = trim(str_replace($passPath, &quot;&quot;, $file-&gt;getPathName()), &quot;/&quot;);
    $manifestData[$key] = sha1_file($file-&gt;getPathName());
}</pre>
<p>Now for the signature&#8230; basically, we sign the <code>manifest.json</code> file using our certificate and password, including Apple&#8217;s WWDR certificate. The binary output is written to <code>signature</code>. However, there’s a problem here: the the binary option for PHP&#8217;s <code>openssl_*</code> functions seems buggy and still generates a text-encoded signature. I&#8217;ve worked around this by calling the shell command from PHP instead:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$signCommand = sprintf(
    &quot;openssl smime -binary -sign -certfile %s -signer %s -inkey %s -in %s -out %s -outform DER -passin pass:%s&quot;,
    APPLE_CERTIFICATE,
    $certPath,
    $certPath,
    $manifestPath,
    $signaturePath,
    $certPassword
);

$signResult = false;
$signOut = array(); // needed but unused
exec($signCommand, $signOut, $signResult);
unset($signOut);</pre>
<p>If the <code>$zip</code> option is enabled (with by default it is) the pass is packed using the <code>ZipArchive</code> class.</p>
<p>To verify the pass, <code>verifyPassSignature()</code> extracts the given pass to a temporary directory and then calls the internal <code>validateManifest()</code> and <code>validateSignature()</code> methods. Both methods must return true.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
foreach ($files as $file) {
    ...

    // Check that each file is present in the manifest
    if (!array_key_exists((string)$file, $manifestData)) {
        throw new \Exception(&quot;No entry in manifest for file '{$file}'&quot;), 506);
    }

    // Check SHA1 hash for each file
    $hash = sha1_file($file-&gt;getPathname());
    if ($hash == false || $hash != $manifestData[(string)$file]) {
        throw new \Exception(
            sprintf(
                &quot;For file %s, manifest's listed SHA1 hash %s doesn't match computed hash, %s&quot;,
                $file,
                $manifestData[(string)$file],
                $hash
            ),
            507
        );
    }
}</pre>
<p>A manifest is valid if the pass directory contains only the files declared inside the manifest, the manifest itself, and the signature file. If a file is missing or there are files not listed then the pass is invalid. Also, the SHA1 hash for each file must match with the one stored in the manifest.</p>
<p>The signature is also validated using <code>openssl</code> in three steps. First we verify the manifest’s contents with its signature. The option <code>-noverify</code> tells OpenSSL to skip the signer’s certificate verification.</p>
<pre class="brush: php; title: ; notranslate">$verifyCommand = sprintf(
    'openssl smime -verify -binary -inform DER -in %s -content %s -noverify 2&gt; /dev/null',
    $signaturePath,
    $manifestPath
);</pre>
<p>Then the certificates are extracted from the signature:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$exportCommand = sprintf(
    'openssl smime -pk7out -in %s -content %s -inform DER -outform PEM',
    $signaturePath,
    $manifestPath
);</pre>
<p>The command&#8217;s output is passed to the internal <code>parseCertificates()</code> method which I won’t discuss here. It uses a mix of OpenSSL and regex to extract certificates from the given data to an array of associative arrays which is used for a certificate-checking loop:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$certs = self::parseCertificates($pemData);
$foundWWDRCert = false;
for ($i = 0; $i &lt; count($certs); $i++) {
    $commonName = $certs[$i]['subject']['CN'];

    if ($commonName == APPLE_CERTIFICATE_CN) {
        $foundWWDRCert = true;
    }
}</pre>
<p><h>The Index Controller</h3>
<p>The controller <code>index.php</code> is responsible for providing both the web-GUI app and the RESTful API. It consists of two URIs: the homepage via GET and the same page via POST. The first page displays only the empty form, but the second is more interesting.</p>
<p>To ensure each email address is unique, it asks Paris which in turn checks the database:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$subscriber = Model::factory('\MyPassbook\Subscriber')
    -&gt;where_equal('email', $memberMail)
    -&gt;find_one();

if ($subscriber !== false) {
    $errors['membermail'] = sprintf(&quot;The email address '%s' is not available&quot;, $memberMail);
}</pre>
<p>The subscriber thumbnail URL is picked from Gravatar:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
if (empty($errors['membermail'])) {
    $memberThumbnail = &quot;https://www.gravatar.com/avatar/&quot; . md5(strtolower(trim($memberMail))) . &quot;?s=60&quot;;
}</pre>
<p>And now it can create a new subscriber:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
try {
    $subscriber = Model::factory('\MyPassbook\Subscriber')-&gt;create(
        array(
            'name' =&gt; $memberName,
            'email' =&gt; $memberMail,
            'created' =&gt; date('Y-m-d H:i:s', $memberSubscription),
            'function' =&gt; $memberFavFunction,
            'picture' =&gt; $memberThumbnail
            )
    );
    $subscriber-&gt;save();
}
catch (\Exception $e) {
    $errors['subscriber'] = &quot;Error creating subscriber profile&quot;;
}</pre>
<p>The pass&#8217;s JSON template file is loaded into <code>$data</code> and all of the placeholders are filled with real user and app data:</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$data['serialNumber'] = $subscriber-&gt;id;
$data['webServiceURL'] = sprintf('https://%s/%s/', $env['SERVER_NAME'], $app-&gt;request()-&gt;getRootUri());
$data['authenticationToken'] = md5($subscriber-&gt;id);
$data['barcode']['message'] = $subscriber-&gt;id;
$data['generic']['primaryFields'][0]['value'] = $subscriber-&gt;name;
$data['generic']['secondaryFields'][0]['value'] = date('Y', $memberSubscription);
$data['generic']['auxiliaryFields'][0]['value'] = $subscriber-&gt;function . '()';
$data['generic']['backFields'][0]['value'] = $subscriber-&gt;id;
$data['generic']['backFields'][1]['value'] = $subscriber-&gt;created;
$data['generic']['backFields'][2]['value'] = $subscriber-&gt;email;</pre>
<p>Using the custom model methods, the new <code>$pass</code> is created with <code>$subscriber-&gt;createPass()</code> and, if everything is right, the <code>$pass</code> can pack itself.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
if ($pass = $subscriber-&gt;createPass($app-&gt;config('passes.passType'), $data)) {
    $pass-&gt;pack(
        $app-&gt;config('passes.path'),
        $app-&gt;config('passes.store'),
        $app-&gt;config('passes.certfile'),
        $app-&gt;config('passes.certpass')
    );

...

}
else {
    $errors['pass'] = 'Unable to create pass';
}</pre>
<p>The <code>pack()</code> method is simple: it makes a temporary copy of the template directory, adds the pass-specific files, and calls <code>PassSigner::signPass()</code> on the working directory. The newly created pass is then sent by email and the <code>pass.php </code>template file is rendered to the user with the download link.</p>
<h3>Going RESTful</h3>
<p>Since a web service URL is embedded inside the pass, Apple&#8217;s specs say that we must implement at least two endpoints for registering and unregistering devices. The URI is always <em>/v1/devices/:deviceId/registrations/:passTypeId/:serialNo</em> and is called via POST for registration and DELETE for unregistration.</p>
<p>The Device ID, Pass Type ID, and Pass Serial Number are received from the URI while the auth token is found in the Authorization header. The auth token must be present in the header and linked to a pass in order to succeed, and a 401 response must be returned in the event of unauthorized access.</p>
<p>During the registration process, a Push Token is sent as the body of the request in JSON format: <code>{"pushToken": <em>&lt;pushToken&gt;</em>}</code>. The registration process creates a new <code>Device</code> object in the database and fills the Device ID and Push Token fields provided. Then a <code>DevicePass</code> object is created to store the relationship between the device and the pass.</p>
<p>If we need to update a pass, we use the Device ID and Push Token to send a push notification request to Apple Push Server (and obviously the update mechanisms need to be implemented as well).</p>
<p>The unregistration URI receives all of the same data except for the Push Token. All references for the given pass are deleted, including devices and relationships.</p>
<h2>Conclusion</h2>
<p>We’ve covered a lot in this article, and there’s still more to explore about Pass management. Feel free to start with the PassSigner library and build on top of it. You can easily create all sorts of Pass applications for you or your clients. Happy coding!</p>
<p><small>Image via <a title="Royalty Free Stock Photos at Fotolia.com" href="http://us.fotolia.com/?utm_source=sitepoint&amp;utm_medium=website_link&amp;utm=campaign=sitepoint" target="_blank">Fotolia</a></small></p>
<img src="http://feeds.feedburner.com/~r/PHPMaster_feed/~4/ji0OTAHaLhk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://phpmaster.com/create-digital-tickets-with-php-and-apple-passbook/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://phpmaster.com/create-digital-tickets-with-php-and-apple-passbook/</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using memcached
Database Caching 15/17 queries in 0.014 seconds using memcached
Object Caching 916/921 objects using memcached
Content Delivery Network via cdn.phpmaster.com

Served from: phpmaster.com @ 2013-06-19 07:48:24 -->
