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

<channel>
	<title>PHP Tip A Day</title>
	<atom:link href="http://www.php-tip-a-day.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.php-tip-a-day.com</link>
	<description>My Daily Discoveries About PHP</description>
	<lastBuildDate>Fri, 27 Jul 2012 02:51:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Summer Hiatus</title>
		<link>http://www.php-tip-a-day.com/summer-hiatus/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=summer-hiatus</link>
		<comments>http://www.php-tip-a-day.com/summer-hiatus/#comments</comments>
		<pubDate>Mon, 02 Jul 2012 02:49:10 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=387</guid>
		<description><![CDATA[Between my kids having a later bedtime during the summer and a medical issue in the family, I don't have time to study PHP and blog about it right now. Both the summer bedtimes and the medical issue should be resolved by early September, and I should have a bunch of new stuff to write…]]></description>
				<content:encoded><![CDATA[<p>Between my kids having a later bedtime during the summer and a medical issue in the family, I don't have time to study PHP <i>and</i> blog about it right now. Both the summer bedtimes and the medical issue should be resolved by early September, and I should have a bunch of new stuff to write about.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/summer-hiatus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: King Floyd and the Seventeen Princes - A Tale of the Observer Pattern</title>
		<link>http://www.php-tip-a-day.com/php-tutorial-king-floyd-and-the-seventeen-princes-a-tale-of-the-observer-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-tutorial-king-floyd-and-the-seventeen-princes-a-tale-of-the-observer-pattern</link>
		<comments>http://www.php-tip-a-day.com/php-tutorial-king-floyd-and-the-seventeen-princes-a-tale-of-the-observer-pattern/#comments</comments>
		<pubDate>Fri, 22 Jun 2012 07:01:37 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=332</guid>
		<description><![CDATA[Since I've been getting positive feedback on design patterns as stories, here's another: Back before horses were invented, the tiny kingdom of Schadenfreude was ruled by good King Floyd and Queen Tillie, who were worried that their son Prince Roscoe would never find a wife. In the neighboring kingdom of Punim, King Marvin had a…]]></description>
				<content:encoded><![CDATA[<p>Since I've been getting positive feedback on design patterns as stories, here's another:<br />
<blockquote>
<p>Back before horses were invented, the tiny kingdom of Schadenfreude was ruled by good King Floyd and Queen Tillie, who were worried that their son Prince Roscoe would never find a wife. In the neighboring kingdom of Punim, King Marvin had a beautiful daughter named Shayna who was an excellent marriage prospect. She was clever, beautiful, and had massive tracts of land. Floyd and Tillie gathered up the royal retainers and ventured out to see King Marvin.</p>
<p>Schadenfreude and Punim were on good terms, although Schadenfreude's diplomats always seemed a little too happy when things went wrong in Punim. King Marvin agreed that the marriage between Roscoe of Schadenfreude and Shayna of Punim would be a good thing.</p>
<p>Now, though Punim was a mostly happy kingdom on its face, there was one source of unhappiness. Only a male of the royal blood could inherit the throne. Since King Marvin had no male children, there was great infighting among his seventeen brothers about who would take the throne when Marvin died. As soon as they were married, it fell upon Roscoe and Shayna to have a son as soon as they could, so that there would be an heir to King Marvin's throne and end the fighting.</p>
<p>The fates smiled upon the couple and Shayna was soon pregnant, but though they visited wizard after wizard, none could say for sure whether Shayna would have a boy or a girl. Shayna was 7 months along when her father, King Marvin, fell gravely ill. His doctors gave him three months to live and his brothers began jockeying for power. But none could make a move until it was known if Princess Shayna and Prince Roscoe's child was a boy or a girl.</p>
<p>Every prince sent an ambassador to the court of King Floyd. Each ambassador had the same request "send your swiftest messenger on your strongest horse to tell my master if the child is a girl. You will be richly rewarded." Since horses had not yet been invented, Floyd found this request puzzling, yet every ambassador made it and Floyd was left in an uncomfortable situation. If he favored one brother over another, that brother might become king and reward him, but that brother might also fail, and that could leave Floyd on bad terms with the brother who succeeded.</p>
<p>Schadenfreude could not afford a spy corps that could return enough information for Floyd to judge which brother he should ally with, so he called for Alan, the royal wizard. Alan listened intently to King Floyd's dilemma and proposed a solution. "I will create a special magic mirror for this birth()." Alan called it "birth()" because the parentheses to him looked like the opening through which the baby would come.</p>
<p>"Every wizard whose master is interested in knowing the results of the birth() can use their magic communication objects to register their intent with the magic mirror. This way we do not have to construct the mirror with foreknowledge of all the other magic objects it must notify. When birth() happens, the mirror will merely run through the list of objects that have registered with it and transmit the event to them. This will happen so quickly, no one prince will be able to claim we showed favor to another."</p>
<p>King Floyd thought this a marvelous solution and commissioned the wizard Alan to build such a mirror. He completed it quickly, using methods he had previously developed to speed its construction. The ambassadors were all sent back to their princes with instructions on how to register with the magic mirror. And when the baby was born, the magic mirror sent "child = boy" to all the registered objects.</p>
<p>Because he made so many brothers unhappy, they named him Joseph. And when he grew up, he invented horses.</p>
<p>The End</p></blockquote>
<p>The first place I recall encountering the observer pattern was not in PHP, but in JavaScript. If you've ever set a listener to fire when an event happened, you've used the observer pattern. Functions or methods are registered with an object so that when it experiences a specific event, it "notifies" the registered functions or methods by calling them. </p>
<p>This is a great example of loose coupling. The object that implements the "subject" part of the observer pattern has no foreknowledge of the other classes/objects that will observe it, so they're not hardcoded into the class. Instead, they're registered or attached as needed at runtime. Going back to JavaScript and HTML, I can create this button:</p>
<pre class="wp-code-highlight prettyprint">&lt;button id=&quot;button1&quot; type=&quot;button&quot; value=&quot;My Button&quot; onClick=&quot;myFunction();&quot;/&gt;</pre>
<p>That's a tightly coupled button that DOESN'T implement the observer pattern, because the function the button will call is hardcoded into the button's HTML. On the other hand, I can register a listener for the button's click event very easily with jQuery.</p>
<pre class="wp-code-highlight prettyprint">&lt;script type=&quot;text/javascript&quot;&gt;
	$(&quot;#button1&quot;).click(function(){
		// some code goes here
	});
&lt;/script&gt;
&lt;button id=&quot;button1&quot; type=&quot;button&quot; value=&quot;My Button&quot;/&gt;
</pre>
<p>Though it's a little more typing to set the listener instead of an onClick handler in the button's instantiation, you can set multiple listeners that will all fire on the click without changing the HTML.</p>
<p>I'm sorry I didn't give sample code for an observer pattern in PHP, but web user interfaces are so observer oriented, it just felt like I had to go with the JS example. Plus, I don't know about you, but I don't have the option of being a "pure" PHP coder. I have to work with JavaScript and jQuery periodically, so mixing things up doesn't hurt as far as I'm concerned.</p>
<p>If you really want a PHP implementation, check out the documentation for the <a href="http://www.php.net/manual/en/class.splsubject.php">SplSubject interface</a>. The SPL (Standard PHP Library) bakes in some language level support for the observer pattern with the SplSubject and <a href="http://www.php.net/manual/en/class.splobserver.php">SplObserver</a> interfaces.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/php-tutorial-king-floyd-and-the-seventeen-princes-a-tale-of-the-observer-pattern/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: Pear DB, Microsoft SQL Server, and the nvarchar Data Type</title>
		<link>http://www.php-tip-a-day.com/php-tutorial-pear-db-microsoft-sql-server-and-the-nvarchar-data-type/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-tutorial-pear-db-microsoft-sql-server-and-the-nvarchar-data-type</link>
		<comments>http://www.php-tip-a-day.com/php-tutorial-pear-db-microsoft-sql-server-and-the-nvarchar-data-type/#comments</comments>
		<pubDate>Thu, 21 Jun 2012 07:01:36 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[Pear]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=326</guid>
		<description><![CDATA[Sorry I've been absent a few days. Stuff got hectic. Before I start, I want to give a shout out to Ian Maddox (a.k.a. @isnoop) for a great presentation to kick off the "Summer of OOP" at the Seattle PHP Meetup last week. And I wanted to let you know that I'll be running another…]]></description>
				<content:encoded><![CDATA[<p>Sorry I've been absent a few days. Stuff got hectic. Before I start, I want to give a shout out to <a href="http://ianmaddox.com/#353/linkedin">Ian Maddox</a> (a.k.a. <a href="https://twitter.com/#!/isnoop">@isnoop</a>) for a great presentation to kick off the "Summer of OOP" at the <a href="http://www.meetup.com/php-49/">Seattle PHP Meetup</a> last week. And I wanted to let you know that I'll be running another design pattern short story tomorrow: "King Floyd and the Seventeen Princes: A Tale of the Observer Pattern".</p>
<p>Nopw to today's tip...</p>
<p>One of the projects making my life hectic was that project to redirect API calls into a database during some scheduled downtime and then pull them all out and run them against the API when it was back up. What one manager had predicted would be 20-40 API calls turned out to be 708. But when it came time to pull them out of the database, some were failing. Turned out that the column holding the data I would pass to the API was being truncated at 256 characters.</p>
<p>Back up to my earliest days of database design where I was taught that using a varchar data type was better than using a text data type because it used less memory and was more indexable. I should probably double check if that's still true, but that's what I read. So though I knew I might store more than 256 chars in that field, I was using Microsoft Sequel Server and I'd read that the nvarchar type could take up to 8,000 characters. So I went with a nvarchar data type with a max size of 2,048 characters for this column.</p>
<p>If I ran my stored process to retrieve data using Server Management Studio, everything came back in full. But in PHP, the results were getting truncated to 256 characters. I pinged the director of web development  to see if he knew why and he said "no, but our database class is just a wrapper for <a href="http://pear.php.net/package/DB/">Pear DB</a>. Maybe you can start there." I did a little googling and found out a fun fact.</p>
<p>Pear DB treats nvarchar like varchar, and though Microsoft lets you store up to 8,000 characters, Pear DB limits what it returns to 256 characters. Now, with 708 rows already stored and this being a production server that I don't have any sort of admin access to, restructuring a live table was not going to be an efficient solution. But I kept googling and found out a fun trick... I could rewrite my SELECT query to recast the nvarchar data type as a text data type in the output.</p>
<p>So I went from:</p>
<pre class="wp-code-highlight prettyprint">SELECT id, method, data, processed FROM [table]</pre>
<p>to...</p>
<pre class="wp-code-highlight prettyprint">SELECT id, method, CONVERT(TEXT,data) as data, processed FROM [table]</pre>
<p>That simple. I updated my retrieval routine with the altered query and no more truncation.</p>
<p>Lesson of the day: Be careful with your MSSQL data types when working with Pear DB.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/php-tutorial-pear-db-microsoft-sql-server-and-the-nvarchar-data-type/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: Raw Encoding</title>
		<link>http://www.php-tip-a-day.com/php-tutorial-raw-encoding/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-tutorial-raw-encoding</link>
		<comments>http://www.php-tip-a-day.com/php-tutorial-raw-encoding/#comments</comments>
		<pubDate>Thu, 14 Jun 2012 07:01:49 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=322</guid>
		<description><![CDATA[Today's tip is quick and dirty. I spent my time mulling over the Observer pattern and a story about a royal wedding, but it just wouldn't come together before bedtime. So today's tip is about rawurlencode(). Encoding is useful when you need to compose a GET URL that has parameters in it containing characters that…]]></description>
				<content:encoded><![CDATA[<p>Today's tip is quick and dirty. I spent my time mulling over the Observer pattern and a story about a royal wedding, but it just wouldn't come together before bedtime.</p>
<p>So today's tip is about <code>rawurlencode()</code>. </p>
<p>Encoding is useful when you need to compose a GET URL that has parameters in it containing characters that are technically illegal to use in a URL (like spaces) or that might mess up your query string (like ampersands and question marks). This is where <code>urlencode()</code> always seemed to come in handy.</p>
<pre class="wp-code-highlight prettyprint">
$customername = &quot;Ted Fischer&quot;;
$customeraddress = &quot;124 Main St.&quot;;
$closestXstreets = &quot;Main &amp; Vincent&quot;;

$displayclientlocationURL = 
   &quot;http://spgulhankmeder.com/mapit?name=&quot; . urlencode($customername).
   &quot;&amp;address=&quot; . urlencode($customeraddress) .
   &quot;&amp;xstreets=&quot; . urlencode($closestXstreets);

echo &quot;&lt;a href=\&quot;$displayclientlocationURL\&quot;&gt;Map it&lt;/a&gt;&quot;;
</pre>
<p>This returns:</p>
<pre class="wp-code-highlight prettyprint">
&lt;a href=&quot;http://spgulhankmeder.com/mapit?name=Ted+Fischer&amp;address=124+Main+St.&amp;xstreets=Main+%26+Vincent&quot;&gt;Map it&lt;/a&gt;</pre>
<p>All the spaces are converted to plusses and the ampersand that's part of content instead of control has been converted to %26.</p>
<p>That might be okay, but I've found out the hard way that not every receiving server is going to convert those pluses back to spaces. Some don't back-convert them, particularly if they're not running PHP. See the spec in <a href="http://www.faqs.org/rfcs/rfc3986.html">RFC 3986</a> says that spaces should be rendered as <code>%20</code>, not as <code>+</code>. If you're in a mixed environment and can't be sure the receiving server will treat pluses as spaces, using <code>rawurlencode</code> will get you the following:</p>
<pre class="wp-code-highlight prettyprint">
&lt;a href=&quot;http://spgulhankmeder.com/mapit?name=Ted%20Fischer&amp;address=124%20Main%20St.&amp;xstreets=Main%20%26%20Vincent&quot;&gt;Map it&lt;/a&gt;</pre>
<p>And that will be understood and decoded properly in more places in my experience. I've known about urlencode() for a while now, but it's raw version is new to me and now I'm sharing it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/php-tutorial-raw-encoding/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: The Legend of the Singleton</title>
		<link>http://www.php-tip-a-day.com/php-tutorial-the-legend-of-the-singleton/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-tutorial-the-legend-of-the-singleton</link>
		<comments>http://www.php-tip-a-day.com/php-tutorial-the-legend-of-the-singleton/#comments</comments>
		<pubDate>Wed, 13 Jun 2012 07:01:52 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=314</guid>
		<description><![CDATA[I'm enjoying this experiment in explaining design patterns through storytelling, so today's is the Singleton Pattern. Long, long ago and far, far away, a king commissioned all his wizards to create a single repository of all the kingdom's knowledge. In the kingdom's language, their word for knowledge was "data" and this repository was supposed to…]]></description>
				<content:encoded><![CDATA[<p>I'm enjoying this experiment in explaining design patterns through storytelling, so today's is <a href="http://www.ibm.com/developerworks/library/os-php-designptrns/#N10124">the Singleton Pattern</a>.</p>
<blockquote><p>Long, long ago and far, far away, a king commissioned all his wizards to create a single repository of all the kingdom's knowledge. In the kingdom's language, their word for knowledge was "data" and this repository was supposed to form the base of all knowledge, so they called it the Great Database. It took the form of a giant bucket in which all the kingdom's knowledge was stored as a pool of information, and it was levitated over the sands of the Great Desert.</p>
<p>To use the Great Database, one would throw a large hose up over the rim of the tub to connect with the pool. They could then add to, retrieve, or even update the knowledge in the pool. In early tests, the magicians made this work flawlessly and the king was overjoyed at his Great Database. He threw a great party to celebrate its creation.</p>
<p>Every school in the kingdom was invited to send one class. Many classes wanted to use the Great Database, but when all their members each threw up a hose, the great weight of so many connections brought the Great Database crashing down. The magicians were called and worked furiously to detach all the hoses and raise the Great Database once more.</p>
<p>To solve this problem of too many hoses, they limited each class to one hose and appointed one member the keeper of the hose. But some classes took a long time to complete all their members' queries of the Great Database because they would throw up the hose before each question and then pull it down after, wasting time and tiring their keeper of the hose. And every time a new class came along, the magicians had to spend time training one of its members in casting and retrieving the hose.</p>
<p>Finally, Ignatz the Fetid conceived of an idea... a single hose. It would be cast by a worker who would manage it and bring it to each class when requested. When no classes needed it, it could be disconnected, but when called by a class, it would be left connected until all the classes' sessions were done and they were cleared.</p>
<p>Because it had to do much work and was rather large, this hose was very heavy. It weighed exactly 2,000 pounds. Since it did not weigh more or less, it was declared that it weighed a "single ton," and that became its name. Over the years, the words ran together and today we know it as the Singleton.</p></blockquote>
<p>The Singleton pattern is a simple form of resource management. Every time you create a resource like a database handle or a filestream, there's a cost in overhead. If you create multiple, you create more overhead. And whenever you release one before you're done, then have to re-establish it, the repetition slows down execution.</p>
<p>So we create a class that manages that resource. Whenever another class requests the resource, the class checks to see if it exists, and if not, it creates it. Then, until execution ends, every class that needs the resource gets it passed to them instead of getting a new one created. By sharing the resource through this manager, the cost of redundant resources or repeated creation/release of resources is mostly eliminated.</p>
<p>Here's a simple singleton:</p>
<pre class="wp-code-highlight prettyprint">
class Database{

    private static $instance;
    private $db;

    private function __construct(){
        /**
         *Create the database connection
         */
        [database connection information]
        $this-&gt;db = mysql_connect($dbserver, 
           $userdbl, $userdba) or die(&quot;could not connect to database&quot;);
        mysql_select_db([name of db],$this-&gt;db);
    }

    public static function getInstance(){
	if(!self::$instance){
	    self::$instance = new Database();
        }
        return self::$instance;
    }
}</pre>
<p>Now this isn't quite the same as in the IBM article. I saw this way of implementing a singleton in another article and liked the idea of making the <code>__construct()</code> method private. That way, no one can instantiate the Database class as an object except the class itself. And because you're passing the Database object instead of simply passing the database connection handle, you can implement some ORM as methods in the object.</p>
<p>Anyhow, I hope you enjoyed this. If you did, please leave a comment, tweet about it, or link to it from your favorite mailing list or social media site.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/php-tutorial-the-legend-of-the-singleton/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: The Allegory of The Factory Pattern</title>
		<link>http://www.php-tip-a-day.com/php-tutorial-the-allegory-of-the-factory-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-tutorial-the-allegory-of-the-factory-pattern</link>
		<comments>http://www.php-tip-a-day.com/php-tutorial-the-allegory-of-the-factory-pattern/#comments</comments>
		<pubDate>Tue, 12 Jun 2012 07:01:08 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[allegories]]></category>
		<category><![CDATA[loose coupling]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=299</guid>
		<description><![CDATA[If you've read the About This Site page, you'll know that instead of pursuing my passion for computers, I got sidetracked into the arts in college. So when it came time for me to learn and explain the Factory Pattern, I thought it might be fun to express it as an allegory... Henry had a…]]></description>
				<content:encoded><![CDATA[<p>If you've read the <A href="/about-this-site/">About This Site</a> page, you'll know that instead of pursuing my passion for computers, I got sidetracked into the arts in college. So when it came time for me to learn and explain the <A href="https://www.ibm.com/developerworks/library/os-php-designptrns/#N10076">Factory Pattern</a>, I thought it might be fun to express it as an allegory...<br />
<blockquote>
<p>Henry had a company that made these new fangled things called automobiles. Now automobiles were made up of a lot of parts, and one of the primary parts they needed was axles. Each axle needed to implement two methods: <code>attachWheels()</code> and <code>turn()</code>.</p>
<p>Steven had a company that made axles. He supplied axles to Henry's assembly line. When Henry first designed his automobile, he thought an axle from a solid piece of hickory would do a really good job. So he printed up a bunch of ordering forms that specified <code>new HickoryWoodAxle()</code> as the part to be used.</p>
<p>One day, over drinks at the country club, Steven was talking with Andrew. Andrew told him "I can supply you with birch at half the cost of hickory and it will be just as strong." Knowing it would be wrong to change the wood without approval, Steven called Henry, who was busy trying to hit rubber frogs into a copper spitoon with a croquet mallet. "Yeah, yeah, whatever," Henry said.</p>
<p>Steven went into production immediately, making axles out of birch. Feeling it would be dishonest to call them <code>HickoryWoodAxle()</code>, he changed the part ID to <code>BirchWoodAxle()</code>. Henry, however, had caught a ship to Bora Bora where he was under the delusion that he was headlining a three-act musical tribute to molybdenum in the basement of an opium den, and forgot to inform his plant to change the order form.</p>
<p>The next time Henry's plant requested a <code>HickoryWoodAxle()</code>, the shipping manager at Steven's plant looked in inventory and said "we don't have any of those." He refused to send Henry's plant a <code>HickoryWoodAxle()</code>, and Henry's plant had to shut down. If only they'd known to order a <code>BirchWoodAxle()</code>, they could have kept production plugging along.</p>
<p>Henry's stockholders met in secret and sent a team of elite Jesuit ninjas to extract Henry from the steppes of Mongolia where he'd become the alpha male in a herd of Yak. When he got back, he called Steven and chewed him out. Steven argued back that Henry should have told his procurement staff of the change. The argument got so heated that they met and had a forty-seven-hour thumb wrestling competition to settle it, but that ended in a draw.</p>
<p>Still, during that competition, they got to talking. "Why does it have to be so difficult," Henry asked. "All I want is an axle. All it has to do is <code>attachWheels()</code> and <code>turn()</code>. I don't care what material you use."</p>
<p>As their thumbs darted back and forth in an intricate dance better explained by a color commentator, their lawyers drew up a contract, defining how Steven and Henry would interface. At Steven's factory, if they got in an order for a <code>new axle()</code>, so long as it could <code>attachWheels()</code> and <code>turn()</code>, that would be good enough. And that way Steven could change his tooling, his materials, or even ship the production overseas. So long as Henry got an <code>axle()</code> that behaved as expected, he'd be happy.</p></blockquote>
<p>So the Factory pattern, as I understand it, is one of the most basic implementations of <b>Loose Coupling</b>. That's where too much knowledge is a dangerous thing. Through the order forms, Henry's assembly line was coded to request a <code>HickoryWoodAxle()</code> object. Every time Steven's plant changed the material, and thus the name of the product class, Henry's assembly line would have to change its order form or the whole system could break down.</p>
<p>So they negotiated an interface...</p>
<pre class="wp-code-highlight prettyprint">
interface IAxle {
	function attachWheels();
	function turn();
}
</pre>
<p>Using that interface as a guide, Steven could create his axle factory that would send an Axle, every time someone sent it a buy order.</p>
<pre class="wp-code-highlight prettyprint">
class Axle implements IAxle {
	private $_material = &quot;ceramic&quot;;
	
	public function attachWheels(){
		return &quot;Wheels attached&quot;;
	}
	
	public function turn(){
		return &quot;Turning&quot;;
	}

	public static function buy(){
		return new Axle();
		}
}
</pre>
<p>Then all you'd need to do is buy an Axle and you can attach Wheels or set it turning.</p>
<pre class="wp-code-highlight prettyprint">
$axle = Axle::buy();
echo &quot;{$axle-&gt;attachWheels()}&lt;br&gt;&quot;;
echo &quot;{$axle-&gt;turn()}&lt;br&gt;&quot;;
</pre>
<p>And there you have it. If you like my idea of pattern allegories, please speak up in the comments. It will encourage me to do more. If you don't, then you're a philistine.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/php-tutorial-the-allegory-of-the-factory-pattern/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: Simulating SOAP Part II</title>
		<link>http://www.php-tip-a-day.com/php-tutorial-simulating-soap-part-ii/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-tutorial-simulating-soap-part-ii</link>
		<comments>http://www.php-tip-a-day.com/php-tutorial-simulating-soap-part-ii/#comments</comments>
		<pubDate>Mon, 11 Jun 2012 07:01:22 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[SOAP]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=283</guid>
		<description><![CDATA[If you read last Thursday's post, you'd know that I was facing an interesting dilemma at work. We have to shut down a server for a day that provides a SOAP-based API that we'd normally send hundreds of requests to in that period. Since simply shutting down the portion of the site that uses that…]]></description>
				<content:encoded><![CDATA[<p>If you read <a href="/idea-faking-a-soap-client/">last Thursday's post</a>, you'd know that I was facing an interesting dilemma at work. We have to shut down a server for a day that provides a SOAP-based API that we'd normally send hundreds of requests to in that period. Since simply shutting down the portion of the site that uses that interface is not an option, I was asked to figure out a way to intercept and store all those calls, so we could execute them later. </p>
<p>I originally thought I was going to have to do a lot of complicated gymnastics, mostly because I hadn't created a SOAP client or server before (I'd mostly done RESTful interfaces that used CURL or <code>file_get_contents()</code> to a URL). But I found out two things:
<ol>
<li  style="margin-bottom:20px;"> The <a href="http://en.wikipedia.org/wiki/Web_Services_Description_Language">WSDL (Web Services Description Language)</a> and the server address weren't tied together. I could leave the WSDL address the same, but set up a simple flag in the SOAP client initiation routine to specify a different server when the system was in maintenance mode.</li>
<li> It's really quite simple to <a href="http://devzone.zend.com/25/php-soap-extension/">set up a SOAP server</a> with the PHP SOAP extensions. It's literally just three lines of code (four, if you want to enable the WSDL cache).</li>
</ol>
<p>Now, you combine that with Friday's post about the <a href="/php-tutorial-london-__calling/"><code>__call()</code> magic method</a> and you've got the makings of your SOAP simulator.</p>
<pre class="wp-code-highlight prettyprint">
class CallCatcher {

	public function __call($method,$args){
		//code to store the method and args
		//to a database		
	}
}

$server = new SoapServer(&quot;http://www.example.com/api/api.wsdl&quot;);
$server-&gt;setClass(&quot;CallCatcher&quot;);
$server-&gt;handle();
</pre>
<p>You can now redirect your SOAP client to hit that service with all its requests instead of the normal server. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/php-tutorial-simulating-soap-part-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: London __call(ing)</title>
		<link>http://www.php-tip-a-day.com/php-tutorial-london-__calling/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-tutorial-london-__calling</link>
		<comments>http://www.php-tip-a-day.com/php-tutorial-london-__calling/#comments</comments>
		<pubDate>Fri, 08 Jun 2012 07:01:49 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[oop]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=279</guid>
		<description><![CDATA[I'm going to talk about my solution to faking SOAP on Monday. First, there's an element of that solution I wanted give its own spotlight dance... __call. There are a selection of function names in OOP PHP called called magic methods. I'm no expert in them and only know about a third, but I'll do…]]></description>
				<content:encoded><![CDATA[<p>I'm going to talk about my solution to faking SOAP on Monday. First, there's an element of that solution I wanted give its own spotlight dance... <code>__call</code>.</p>
<p>There are a selection of function names in OOP PHP called called <a href="http://php.net/manual/en/language.oop5.magic.php">magic methods</a>. I'm no expert in them and only know about a third, but I'll do my best to describe what they do and how they work in a nutshell. </p>
<p>They are probably best described as event placeholders. Your classes will work without them. Your objects will instantiate without them. But if you want to make sure your class/object does something specific when a specific event occurs, you set up a function using the name reserved for magic method that corresponds to that event.</p>
<p>For example, the most famous magic method is __construct. When you instantiate an object based on a class, any code you want to run at instantiation is in there. A little less famous is __call. This is the method that gets invoked whenever you try to call a method that isn't in your class.</p>
<p>This is great if you're setting up an API and you want to have a handler for misnamed calls or some other error handling when a call doesn't correspond to an existing method. It's also great for when you want to... wait for it... fake a SOAP API without replicating all of its methods.</p>
<p>One of the elements of my SOAP capturing fake-out is that my SOAP impostor has ONE primary method...</p>
<pre class="wp-code-highlight prettyprint">
class soapImpostor{

   public function __call($method,$args){
       // code to save the info in
       // $method and $args for later use
   }
}</pre>
<p>I'll go into how the SOAP Impostor is built on Monday. But for now, I'm a little enamored with __call, and wanted to share.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/php-tutorial-london-__calling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Idea: Faking A SOAP Client</title>
		<link>http://www.php-tip-a-day.com/idea-faking-a-soap-client/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=idea-faking-a-soap-client</link>
		<comments>http://www.php-tip-a-day.com/idea-faking-a-soap-client/#comments</comments>
		<pubDate>Thu, 07 Jun 2012 07:01:36 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=273</guid>
		<description><![CDATA[Part of the refactoring I'm working on at work is not just a speed improvement. We're going to have a series of outages where a third party server that provides services to us will not be available. During that time, we don't want to simply turn off all the services it's associated with. So we…]]></description>
				<content:encoded><![CDATA[<p>Part of the refactoring I'm working on at work is not just a speed improvement. We're going to have a series of outages where a third party server that provides services to us will not be available. During that time, we don't want to simply turn off all the services it's associated with. So we want to capture the requests we'd send to the third party system, store them, and send them when it's back up. We set a flag that's accessible to the class responsible for brokering API calls to the client, it switches from "send" to "store". Unset the flag and we're back.</p>
<p>Some early research on short circuiting a SOAP client and intercepting its calls was no help. Second thought was doing something like this to the API broker class's 16 methods. </p>
<pre class="wp-code-highlight prettyprint">if($maintenance_mode) {
   [store the call}
  } else {
   [do the call as normal]
 }</pre>
<p>But it hit me while watching TV with my wife tonight (yay, "Royal Pains" is back) that my problem starts when the SOAP client is istantiated for handling the requests, so what if I used the regular SOAP client for every day activities, but created my own for when maintenance mode is on.</p>
<p>So the question for me to investigate at work is whether I want to simply create a class that will simulate a SOAP object, or essentially build an API to my storage interface, build my own WSDL for it, and then just substitute my WSDL for the normal one when the maintenance flag is turned on. What's it gonna be?</p>
<p>That is my experimentation at work tomorrow, when I'm not busy fielding the latest batch of design tweaks for newsletter templates that shall remain nameless. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/idea-faking-a-soap-client/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Under The Weather</title>
		<link>http://www.php-tip-a-day.com/under-the-weather/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=under-the-weather</link>
		<comments>http://www.php-tip-a-day.com/under-the-weather/#comments</comments>
		<pubDate>Tue, 05 Jun 2012 07:01:00 +0000</pubDate>
		<dc:creator>Greg Bulmash</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.php-tip-a-day.com/?p=269</guid>
		<description><![CDATA[Went to the Everett Software Developers meet-up to discuss What's in a Language, and I'm feeling a little under the weather. Antihistamines are making me feel a little drunk. I have a big refactoring project at work I'll talk about tomorrow. What I'll leave with is this... PHP is the first girlfriend for many of…]]></description>
				<content:encoded><![CDATA[<p>Went to the Everett Software Developers meet-up to discuss <a href="http://www.meetup.com/Everett-Software-Developers/events/60790972/">What's in a Language</a>, and I'm feeling a little under the weather. Antihistamines are making me feel a little drunk.</p>
<p>I have a big refactoring project at work I'll talk about tomorrow.</p>
<p>What I'll leave with is this... PHP is the first girlfriend for many of us, but we programmers are a fickle lot. We either try to keep a girlfriend on the side or want to move onto the new sexy. What's the language that you can't stop checking out? For me it's JavaScript game engines and frameworks.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.php-tip-a-day.com/under-the-weather/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
