Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

article reformatting

  • Loading branch information...
commit 39009d91f74fe101b3ce27eb09077bb58887ea7d 1 parent 0b78c16
@salathe authored
View
14 _posts/2007-09-19-php5-method-chaining.markdown
@@ -59,7 +59,7 @@ class Person
{% endhighlight %}
Now, we can create a new `Person` (see example below) and give them a name and
-age. Using the `introduce` method, the person can them introduce themselves.
+age. Using the `introduce()` method, the person can them introduce themselves.
{% highlight php startinline %}
// We'll be creating me, digitally.
@@ -82,7 +82,7 @@ need to add two lines of code to the basic class above to enable us to write a
chain, and the second line is a repeat of the first! How's it done? Quite
simply we need to return the `Person` object from each method. At the moment,
none of the methods actually return anything so we'll amend that now. We just
-need to add `return $this;` to the methods `setName` and `setAge`.
+need to add `return $this;` to the methods `setName()` and `setAge()`.
The amended `Person` class is as follows:
@@ -132,7 +132,7 @@ $peter->setName('Peter')->setAge(23)->introduce();
{% endhighlight %}
That example will produce exactly the same output as our regular, boring example
-earlier! All because we return the `Person` object in the `setName/Age` methods.
+earlier! All because we return the `Person` object in the `setName/Age()` methods.
## How does that work?
@@ -145,13 +145,13 @@ Peter, my name and returns `$this` -- that is, the `$peter` object.
So at the moment Peter has his name, but no age!
Next up comes `->setAge(23)`. Because we're chained with the previous method,
-PHP interprets the code and says "execute the `setAge` method belonging to
+PHP interprets the code and says "execute the `setAge()` method belonging to
whatever was returned from the previous method." In this case, PHP executes
the `setAge` method belonging to our `Person` object, `$peter`.
-The exact same thing happens when we finally call the `introduce` method.
-PHP executes the `introduce` method belonging to whatever was returned from
-the `setAge` method call: `$peter`.
+The exact same thing happens when we finally call the `introduce()` method.
+PHP executes the `introduce()` method belonging to whatever was returned from
+the `setAge()` method call: `$peter`.
Hopefully, that's at least a bit clear and I'll let you mull over this
confusing (until you _get_ it) subject for a while. I'll leave you with the
View
44 _posts/2008-01-12-php-vars-curly-braces.markdown
@@ -3,28 +3,42 @@ layout: post
title: 'PHP Variable Names: Curly Brace Madness'
excerpt: Having fun with a quirkier side of PHP syntax.
---
-Most PHP coders will know that one is able to specify variable names in the following format, generally within double-quoted strings, however much they frown on it:
+Most PHP coders will know that one is able to specify variable names in the
+following format, generally within double-quoted strings, however much
+they frown on it:
-<pre lang="PHP">$str = "Hello ${username}, you look nice today.";</pre>
+{% highlight php startinline %}
+$str = "Hello ${username}, you look nice today.";
+{% endhighlight %}
However, that's not the only way to use the brace syntax!
-<a id="more"></a><a id="more-18"></a>Straying away from that common usage, it is perfectly reasonable to use the same format in a normal assignment operation:
+Straying away from that common usage, it is perfectly reasonable to use the
+same format in a normal assignment operation:
-<pre lang="PHP">// Same as $str = 'Hello Peter';
-${'str'} = 'Hello Peter';</pre>
+{% highlight php startinline %}
+// Same as $str = 'Hello Peter';
+${'str'} = 'Hello Peter';
+{% endhighlight %}
-Now, moving into the bizzare, the string value within the curly braces can be any expression which results in a <a href="http://php.net/variables#language.variables.basics">valid variable name</a> (and more, see later)!
+Now, moving into the bizzare, the string value within the curly braces can
+be any expression which results in a [valid variable name][variables]
+(and more, see later)!
-<pre lang="PHP">// Each are the same as $str = 'Hello Peter';
+{% highlight php startinline %}
+// Each are the same as $str = 'Hello Peter';
${'s'.'t'.'r'} = 'Hello Peter';
${substr('string', 0, 3)} = 'Hello Peter';
${ 'a' == 'b' ? 'rts' : 'str' } = 'Hello Peter';
-</pre>
+{% endhighlight %}
-Finally, lets get really crazy. The strings within the curly braces needn't necessarily strictly adhere to the normal variable naming conventions! Since the curly braces literally mean "evaluate my contents as a string", we can play around even more!
+Finally, lets get really crazy. The strings within the curly braces
+needn't necessarily strictly adhere to the normal variable naming conventions!
+Since the curly braces literally mean "evaluate my contents as a string", we
+can play around even more!
-<pre lang="PHP">// You can't access these with 'normal' global variables,
+{% highlight php startinline %}
+// You can't access these with 'normal' global variables,
// but the curly brace form works as does getting at them
// via the $GLOBALS superglobal variable!
// Values are converted to strings which is why 0xFF => '255', etc.
@@ -33,6 +47,12 @@ ${0xFF} = 'Hello Peter'; // $GLOBALS['255']
${2 + 2} = 'Hello Peter'; // $GLOBALS['4']
${'Hello Peter'} = 'Hello Peter'; // $GLOBALS['Hello Peter']
${'cats, pet food, dogs'} = 'Hello Peter'; // $GLOBALS['cats, pet food, dogs']
-</pre>
+{% endhighlight %}
-I'm pretty sure these weird variable names serve absolutely no practical purpose, but it's interesting to know of little quirks like this (well, interesting for weirdos like me). Have a play around yourself, remembering that you can <code>print_r()</code> or <code>var_dump()</code> the superglobal <code>$GLOBALS</code> or even use <code>get_defined_vars()</code> to find out the variable names that have been created.
+I'm pretty sure these weird variable names serve absolutely no practical
+purpose, but it's interesting to know of little quirks like this (well,
+interesting for weirdos like me). Have a play around yourself, remembering
+that you can `print_r()` or `var_dump()` the superglobal `$GLOBALS` or even
+use `get_defined_vars()` to find out the variable names that have been created.
+
+ [variables]: http://php.net/variables#language.variables.basics
View
106 _posts/2008-01-13-get-file-extension-comparison.markdown
@@ -4,11 +4,19 @@ title: PHP Get File Extension
excerpt: There are numerous ways to get a file extension in PHP.
Learn how to do it right, by using the <code>pathinfo()</code> function.
---
-Over time, I've seen a wide range of scripts which for one reason or another have had the need to grab the extension from a file name or path (<em>E.g. "gif" from "mypic.gif"</em>). Oftentimes the solution tends to fall back on what the task appears to need: string manipulation. Though, as you'll see, this may not be the best approach to take.
-
-<a id="more"></a><a id="more-19"></a>To make things a little clearer for people who can visualise code more easily than paragraphs of text, here are a few examples of what I've seen used in the past. The samples are mostly compacted onto a single line but if you're not comfortable with multiple things happening in one line, feel free to expand them into multiple steps. In all cases, <code>$ext</code> ends up being "<em>gif</em>" .
-
-<pre lang="PHP">
+Over time, I've seen a wide range of scripts which for one reason or another
+have had the need to grab the extension from a file name or path: e.g. "gif"
+from "mypic.gif". Oftentimes the solution tends to fall back on what the task
+appears to need: string manipulation. Though, as you'll see, this may not be
+the best approach to take.
+
+To make things a little clearer for people who can visualise code more easily
+than paragraphs of text, here are a few examples of what I've seen used in the
+past. The samples are mostly compacted onto a single line but if you're not
+comfortable with multiple things happening in one line, feel free to expand
+them into multiple steps. In all cases, `$ext` ends up being _gif_.
+
+{% highlight php startinline %}
$filename = 'mypic.gif';
// 1. The "explode/end" approach
@@ -28,42 +36,70 @@ $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
-</pre>
-
-Forgetting approach number 5 (the "never use this" approach!), they seem fairly reasonable ways of parsing the <code>$filename</code> string and grabbing the extension. So much so that those approaches can be found dotted around the interweb when people ask the question "<a href="http://www.google.com/search?q=how+to+get+the+file+extension+in+PHP%3F">How to get the file extension in PHP?</a>"
-
-<h3>Speed, baby, speed!</h3>
-
-Because these are commonly used snippets of code, I decided to pitch them against each other and find out which was the most efficient--by that I simply mean the fastest processing--method just to satisfy my curiosity. The exact details of how they were tested I don't plan to go into in this post, but here is what I found. On order of fastest to slowest were:
-
-<ol>
- <li><strong>strrchr</strong></li>
- <li>closely followed by <strong>strrpos</strong></li>
- <li>then <strong>preg_replace</strong></li>
- <li>with <strong>explode/end</strong> coming in almost twice as slow as the str* methods</li>
-</ol>
-
-Great, so the idea is to use the <code>$ext = substr(strrchr($filename, '.'), 1);</code> approach from now on? Hold on there sonny boy, not so fast! There is another contender which has not been considered yet (though some of you would have been screaming his name from the start). Time to introduce the <code>pathinfo</code> function.
-
-<h3>"Hello", says pathinfo.</h3>
-
-<code>Pathinfo</code> does a number of things, depending on what we ask of it, but put simply it returns (path) information about a filepath. Full details can be found on the handy dandy <a href="http://php.net/pathinfo">pathinfo page</a> in the PHP manual. Explore the PHP manual page when you get time, but for the purpose of this blog post I'll hone in to one specific use of the function: getting the file extension. In order to do that, we simply call the function passing along the full filename and a 'flag' (a constant which dictates the behaviour of the function) asking for the extension only.
-
-<pre lang="PHP">
+{% endhighlight %}
+
+Forgetting approach number 5 (the "never use this" approach!), they seem fairly
+reasonable ways of parsing the `$filename` string and grabbing the extension.
+So much so that those approaches can be found dotted around the interweb when
+people ask the question "[How to get the file extension in PHP?][google]"
+
+## Speed, baby, speed!
+
+Because these are commonly used snippets of code, I decided to pitch them
+against each other and find out which was the most efficient--by that I simply
+mean the fastest processing--method just to satisfy my curiosity. The exact
+details of how they were tested I don't plan to go into in this post, but here
+is what I found. On order of fastest to slowest were:
+
+* **strrchr**
+* closely followed by **strrpos**
+* then **preg_replace**
+* with **explode/end** coming in almost twice as slow as the str* methods
+
+Great, so the idea is to use the `$ext = substr(strrchr($filename, '.'), 1);`
+approach from now on? Hold on there sonny boy, not so fast! There is another
+contender which has not been considered yet (though some of you would have been
+screaming his name from the start). Time to introduce the `pathinfo()` function.
+
+## "Hello", says pathinfo.
+
+`pathinfo()` does a number of things, depending on what we ask of it, but put
+simply it returns (path) information about a filepath. Full details can be
+found on the handy dandy [pathinfo page][pathinfo] in the PHP manual. Explore
+the PHP manual page when you get time, but for the purpose of this blog post
+I'll hone in to one specific use of the function: getting the file extension.
+In order to do that, we simply call the function passing along the full
+filename and a 'flag' (a constant which dictates the behaviour of the function)
+asking for the extension only.
+
+{% highlight php startinline %}
$filename = 'mypic.gif';
$ext = pathinfo($filename, PATHINFO_EXTENSION);
-</pre>
+{% endhighlight %}
+
+That's all there is to it! In my opinion, this approach 'reads' much more
+easily than the mess of nested function calls and playing around with string
+positions, regular expressions, etc.. It is concise and to the point:
+call pathinfo and only give me back the extension. Simple.
-That's all there is to it! In my opinion, this approach 'reads' much more easily than the mess of nested function calls and playing around with string positions, regular expressions, etc.. It is concise and to the point: call pathinfo and only give me back the extension. Simple.
+Now for the icing on the cake. When pitched against the other methods detailed
+above, this call to pathinfo beats all of the others into submission. At least
+in my testing, it is the fastest method of all (though in random hiccups strrchr
+does win in around 1% of tests) being on average 1/10<sup>th</sup> faster than
+even the strrchr approach.
-Now for the icing on the cake. When pitched against the other methods detailed above, this call to pathinfo beats all of the others into submission. At least in my testing, it is the fastest method of all (though in random hiccups strrchr does win in around 1% of tests) being on average 1/10<sup>th</sup> faster than even the strrchr approach.
+## Summary, or "the bit lazy people should read"
-<h3>Summary, or "the bit lazy people should read"</h3>
+So, to cut a long blog post short, the method that I'll be using to grab
+the file extension is simply:
-So, to cut a long blog post short, the method that I'll be using to grab the file extension is simply:
-<pre lang="PHP">
+{% highlight php startinline %}
$filename = 'mypic.gif';
$ext = pathinfo($filename, PATHINFO_EXTENSION);
-</pre>
+{% endhighlight %}
+
+What do you currently use? Have you had any problems using pathinfo,
+any particular quirks or annoyances?
-What do you currently use? Have you had any problems using pathinfo, any particular quirks or annoyances?
+ [google]: http://www.google.com/search?q=how+to+get+the+file+extension+in+PHP%3F
+ [pathinfo]: http://php.net/pathinfo
View
75 _posts/2008-01-22-imagecreatefrom-string-remote.markdown
@@ -3,16 +3,40 @@ layout: post
title: PHP Imagecreate & Different File Types
excerpt: Using <code>imagecreatefromstring()</code> to create a GD image.
---
-For a recent little bit of PHP scripting, I wanted to grab an image off of a remote server (not for any nefarious purpose!) and manipulate it in PHP (with <a href="http://php.net/image">GD</a>). <a id="more"></a><a id="more-20"></a>The actual manipulation was trivial, all I wanted to do was reduce the dimensions of the remote image, so I won't go into that in this post.
+For a recent little bit of PHP scripting, I wanted to grab an image off of a
+remote server (not for any nefarious purpose!) and manipulate it in PHP
+(with [GD][gd]). The actual manipulation was trivial, all I wanted to do was
+reduce the dimensions of the remote image, so I won't go into that in this post.
-However, when thinking about getting the remote file and making it a GD image there were a few options available. The 'normal' methods of creating GD images from files seemed like a reasonable start: imagecreatefrom<em>filetype</em>, where <em>filetype</em> is one of <em>png, jpeg, gif</em> (or even gd2, wbmp, xbm, xpm...). At first glance everything seems cool, these functions can even grab the file from remote servers. Assuming http://example.org/photo.jpg is a valid image, then <code>imagecreatefromjpeg('http://example.org/photo.jpg');</code> would work fine (if <code>allow_url_fopen</code> is enabled in php.ini).
+However, when thinking about getting the remote file and making it a GD image
+there were a few options available. The 'normal' methods of creating GD
+images from files seemed like a reasonable start:
+imagecreatefrom<var>filetype</var>, where _filetype_ is one of _png, jpeg, gif_
+(or even gd2, wbmp, xbm, xpm...). At first glance everything seems cool,
+these functions can even grab the file from remote servers. Assuming
+http://example.org/photo.jpg is a valid image, then the following
+would work fine (if `allow_url_fopen` is enabled in php.ini).
-<h3>First Hurdle</h3>
+{% highlight php startinline %}
+imagecreatefromjpeg('http://example.org/photo.jpg');
+{% endhighlight %}
-The first problem that came to light was that I never really knew what kind of image would be returned from the remote server. All of the remote image names were <em>something</em>.gif but the actual image could be anything from a gif to jpeg to png (the most common web image types). Determining the image type isn't particularly trivial, you can easily grab the MIME type from the remote server and use the appropriate <code>imagecreatefrom...</code> function but there's no guaranteeing that the server would necessarily throw out the correct MIME (from testing, this didn't appear to be a problem but one must always assume that the MIME can be telling fibs).
+## First Hurdle
-I could have ploughed ahead, assuming everything was all ok and grab the remote image in a <code>switch</code> statement (or series of <code>if</code>s, etc.) like so:
-<pre lang="PHP">
+The first problem that came to light was that I never really knew what kind
+of image would be returned from the remote server. All of the remote image
+names were _something_.gif but the actual image could be anything from a gif
+to jpeg to png (the most common web image types). Determining the image type
+isn't particularly trivial, you can easily grab the MIME type from the remote
+server and use the appropriate `imagecreatefrom...` function but there's no
+guaranteeing that the server would necessarily throw out the correct MIME
+(from testing, this didn't appear to be a problem but one must always assume
+that the MIME can be telling fibs).
+
+I could have ploughed ahead, assuming everything was all ok and grab the
+remote image in a `switch` statement (or series of `if`s, etc.) like so:
+
+{% highlight php startinline %}
$remote_file = 'http://www.talkphp.com/avatars/salathe.gif';
$headers = get_headers($remote_file, 1);
@@ -30,19 +54,40 @@ switch ($headers['Content-Type'])
default:
die('Invalid image type');
}
-</pre>
+{% endhighlight %}
-Now, that's a huge mess and whilst things could easily be tidied up by using <em>variable functions</em> or some other structure like that but the problem would still exist of looking at the mime type to determine which function to use. Wouldn't it be great if there was a function which would create an image regardless of the image type fed into it? Worry not, such a function exists (but strangely isn't discussed very often).
+Now, that's a huge mess and whilst things could easily be tidied up by using
+_variable functions_ or some other structure like that but the problem would
+still exist of looking at the mime type to determine which function to use.
+Wouldn't it be great if there was a function which would create an image
+regardless of the image type fed into it? Worry not, such a function exists
+(but strangely isn't discussed very often).
-<h3>Introducing Imagecreatefromstring()</h3>
+## Introducing Imagecreatefromstring()
-Grabbing the remote image from the server is really easy using <code>file_get_contents</code> (or even cURL if you like). Once you have the file's raw contents, those can be fed directly into <code>imagecreatefromstring</code> and the function will return a nice, new GD image. Easy peasy!
+Grabbing the remote image from the server is really easy using
+`file_get_contents()` (or even cURL if you like). Once you have the
+file's raw contents, those can be fed directly into `imagecreatefromstring()`
+and the function will return a nice, new GD image. Easy peasy!
-If you want to be really, really concise (forgetting error handling, etc. for a moment) it's a simple one-liner:
-<pre lang="php">
+If you want to be really, really concise (forgetting error handling, etc. for a
+moment) it's a simple one-liner:
+
+{% highlight php startinline %}
$image = imagecreatefromstring(file_get_contents('http://www.talkphp.com/avatars/salathe.gif'));
-</pre>
+{% endhighlight %}
+
+How cool is that? No need for ugly MIME type checking and calling different
+functions based on that; the `imagecreatefromstring()` function can autodetect
+JPEG, PNG, GIF, WBMP, and GD2 images (so long as your PHP build supports
+whichever type) without any hassle.
-How cool is that? No need for ugly MIME type checking and calling different functions based on that; the <code>imagecreatefromstring</code> function can autodetect JPEG, PNG, GIF, WBMP, and GD2 images (so long as your PHP build supports whichever type) without any hassle.
+A final note, there are comments around regarding the memory consumption of
+`imagecreatefromstring()` and I have to admit that I've really not tested that
+side of things at all. I like to use a lot of caching on my side of things
+anyway, so the number of times that `imagecreatefromstring()` is being called
+in the script I mentioned at the beginning of this post is very infrequent: in
+the region of once every couple of days! The main point here was to offer up
+an alternative solution, which may or may not be useful to you at some point.
-A final note, there are comments around regarding the memory consumption of <code>imagecreatefromstring</code> and I have to admit that I've really not tested that side of things at all. I like to use a lot of caching on my side of things anyway, so the number of times that <code>imagecreatefromstring</code> is being called in the script I mentioned at the beginning of this post is very infrequent: in the region of once every couple of days! The main point here was to offer up an alternative solution, which may or may not be useful to you at some point.
+ [gd]: http://php.net/image
View
23 _posts/2008-02-29-elephpant.markdown
@@ -3,11 +3,24 @@ layout: post
title: ElePHPant
excerpt: Everyone loves a furry blue elephpant.
---
-Well, a slightly less code-minded blog entry now just noting the hugely momentous occasion that is the arrival of my very own ElePHPant. For those not in the know, he's quite simply a plush toy version of the infamous PHP elephant logo. For tonnes of fun pics, you can take a look at <a href="http://flickr.com/photos/tags/elephpant">ElePHPant on Flickr</a>.
+Well, a slightly less code-minded blog entry now just noting the hugely
+momentous occasion that is the arrival of my very own ElePHPant.
+ For those not in the know, he's quite simply a plush toy version of the
+ infamous PHP elephant logo. For tonnes of fun pics, you can take a look at
+ [ElePHPant on Flickr][flickr].
-Here's a quick pic of my own ElePHPant reading a French book printed in the 1940s:
-<a href="http://flickr.com/photos/cowburn/2296498394/"><img class="centered" src="http://farm4.static.flickr.com/3166/2296498394_4f742c7642_m.jpg" alt="ElePHPant on Flickr" /></a>
+Here's a quick pic of my own ElePHPant reading a French book printed in
+the 1940s:
-Right now, he's sitting atop the screen on my Macbook Pro, making sure I don't make any spelling mistakes. :)
+[![ElePHPant on Flickr](http://farm4.static.flickr.com/3166/2296498394_4f742c7642.jpg)][photo]
-P.S. Whilst we're on the not-so-serious side of posting, I finally upgraded to OS X 10.5 (Leopard) this week. I spent the best part of a day backing up essential files and documents only to have the installation process go super smooth without so much as a hiccup. Thanks Apple!
+Right now, he's sitting atop the screen on my Macbook Pro, making sure I don't
+make any spelling mistakes. :)
+
+P.S. Whilst we're on the not-so-serious side of posting, I finally upgraded
+to OS X 10.5 (Leopard) this week. I spent the best part of a day backing up
+essential files and documents only to have the installation process go super
+smooth without so much as a hiccup. Thanks Apple!
+
+ [flickr]: http://flickr.com/photos/tags/elephpant
+ [photo]: http://flickr.com/photos/cowburn/2296498394/
View
86 _posts/2008-11-29-download-speed-php-curl.markdown
@@ -3,15 +3,17 @@ layout: post
title: Server download speed using PHP cURL
excerpt: Using cURL to get an idea of the download speed of your web server.
---
-I've been meaning to add a few snippets of code to the blog, just to archive them to save my own memory but who knows, they may prove useful to someone else.
+I've been meaning to add a few snippets of code to the blog, just to archive
+them to save my own memory but who knows, they may prove useful to someone else.
-This particular one uses cURL to get an idea of the download speed of your web server but is more a demonstration of grabbing the extra information about a cURL transaction which people rarely take a look at. The code was first posted in a similar topic <a href="http://www.sitepoint.com/forums/showthread.php?t=581410">on Sitepoint</a>.
+This particular one uses cURL to get an idea of the download speed of your web
+server but is more a demonstration of grabbing the extra information about a
+cURL transaction which people rarely take a look at. The code was first posted
+in a similar topic [on Sitepoint][sitepoint].
-<a id="more"></a><a id="more-49"></a>
+## PHP Snippet
-<h3>PHP Snippet</h3>
-
-<pre lang="php">
+{% highlight php %}
<?php error_reporting(E_ALL | E_STRICT);
// Initialize cURL with given url
@@ -49,37 +51,41 @@ foreach ($info as $label => $value)
{
printf("%-30s %s\n", $label, $value);
}
-</pre>
-
-<h3>Example Output</h3>
-<pre lang="plain">
-Downloaded 6576848 bytes in 16.2153 seconds.
-Which is 3.0944 mbps
-CURL said 3.0755 mbps
-
-
-curl_getinfo() said:
----------------------------------------------------------------------------------------------
-url http://download.bethere.co.uk/images/61859740_3c0c5dbc30_o.jpg
-content_type image/jpeg
-http_code 200
-header_size 263
-request_size 198
-filetime -1
-ssl_verify_result 0
-redirect_count 0
-total_time 16.314966
-namelookup_time 0.000287
-connect_time 0.021524
-pretransfer_time 0.021595
-size_upload 0
-size_download 6576848
-speed_download 403117
-speed_upload 0
-download_content_length 6576848
-upload_content_length 0
-starttransfer_time 0.056275
-redirect_time 0
-</pre>
-
-As you can see from the example output, there's a miniature treasure trove of information about the cURL transaction which is particularly helpful for the purposes of reporting on the speed and other statistics of the download. Do you ever bother to take a look at the information from your cURL calls?
+{% endhighlight %}
+
+## Example Output
+
+ Downloaded 6576848 bytes in 16.2153 seconds.
+ Which is 3.0944 mbps
+ CURL said 3.0755 mbps
+
+
+ curl_getinfo() said:
+ ---------------------------------------------------------------------------------------------
+ url http://download.bethere.co.uk/images/61859740_3c0c5dbc30_o.jpg
+ content_type image/jpeg
+ http_code 200
+ header_size 263
+ request_size 198
+ filetime -1
+ ssl_verify_result 0
+ redirect_count 0
+ total_time 16.314966
+ namelookup_time 0.000287
+ connect_time 0.021524
+ pretransfer_time 0.021595
+ size_upload 0
+ size_download 6576848
+ speed_download 403117
+ speed_upload 0
+ download_content_length 6576848
+ upload_content_length 0
+ starttransfer_time 0.056275
+ redirect_time 0
+
+As you can see from the example output, there's a miniature treasure trove of
+information about the cURL transaction which is particularly helpful for the
+purposes of reporting on the speed and other statistics of the download.
+Do you ever bother to take a look at the information from your cURL calls?
+
+ [sitepoint]: http://www.sitepoint.com/forums/showthread.php?t=581410
View
67 _posts/2009-03-15-tiny-little-gifs.markdown
@@ -4,29 +4,62 @@ title: Tiny Little GIFs
excerpt: Thirty-six little bytes, and nothing much to see. My attempt
at creating the tiniest transparent GIF image possible.
---
-Early this morning, Paul Bonser write a neat little article (<a href="http://blog.paulbonser.com/2009/03/15/the-tiniest-gif-ever/" rel="external">The Tiniest GIF ever</a>) on his blog about reducing the size of GIF images to their bare minimum number of bytes.
+Early this morning, Paul Bonser write a neat little article
+([The Tiniest GIF ever][bonser]) on his blog about reducing the size of GIF
+images to their bare minimum number of bytes.
-Starting off with a 43 byte image produced in image editor GIMP, he describes the process of removing bytes that aren't particularly necessary with reference to the <a href="http://www.w3.org/Graphics/GIF/spec-gif89a.txt">GIF specification</a>. The end result is a working, fully transparent GIF image in only 37 bytes with two further size reductions producing a fixed colour (35 bytes) and an "I'm feeling lucky" colour (26 bytes).
+Starting off with a 43 byte image produced in image editor GIMP, he describes
+the process of removing bytes that aren't particularly necessary with reference
+to the [GIF specification][gif]. The end result is a working, fully transparent
+GIF image in only 37 bytes with two further size reductions producing a fixed
+colour (35 bytes) and an "I'm feeling lucky" colour (26 bytes).
-Since it's a Sunday, and I had nothing better to do, I also figured it was about time to delve into the guts of GIF images and see if I could come to the same conclusions that Paul had with regards to putting GIF on a diet.<a id="more"></a><a id="more-120"></a>
+Since it's a Sunday, and I had nothing better to do, I also figured it was about
+time to delve into the guts of GIF images and see if I could come to the same
+conclusions that Paul had with regards to putting GIF on a diet.
-Starting with a 43 byte, single-pixel, transparent GIF exported from Photoshop (sorry no GIMP installed on here) I followed the same process as Paul. Because I'm a PHP coder, that made sense to me to do the byte tweaking—sure a hex editor would do fine, but PHP is my chosen tool. Sure enough, thanks to the great instructions I was able to reproduce exactly the same results as Paul found and more importantly, now I know precisely how GIF images are constructed which is something I didn't know (other than a basic idea of there being a header, image data, etc.) before today.
+Starting with a 43 byte, single-pixel, transparent GIF exported from Photoshop
+(sorry no GIMP installed on here) I followed the same process as Paul. Because
+I'm a PHP coder, that made sense to me to do the byte tweaking—sure a hex editor
+would do fine, but PHP is my chosen tool. Sure enough, thanks to the great
+instructions I was able to reproduce exactly the same results as Paul found and
+more importantly, now I know precisely how GIF images are constructed which is
+something I didn't know (other than a basic idea of there being a header,
+image data, etc.) before today.
-I also arrived at the same conclusion as Paul, after much byte-pushing and shoving. 26 bytes is as small as things are going to get (until someone more brainy than the both of us shares their own findings).
+I also arrived at the same conclusion as Paul, after much byte-pushing and
+shoving. 26 bytes is as small as things are going to get (until someone more
+brainy than the both of us shares their own findings).
-On the transparent GIF, Paul said, "So there you go, the tiniest <strong>transparent</strong> GIF possible (if you can make one smaller, let me know)." It's not much but I did manage to eek out an extra byte from the 37 byte transparent image by removing one byte out of the LZW compressed image data portion of the file.
+On the transparent GIF, Paul said, "So there you go, the tiniest **transparent**
+GIF possible (if you can make one smaller, let me know)." It's not much but I
+did manage to eek out an extra byte from the 37 byte transparent image by
+removing one byte out of the LZW compressed image data portion of the file.
-So there you go, the tiniest transparent GIF possible at <strong>36</strong> bytes. (Again, like Paul, do let me know if you can make one smaller!).
+So there you go, the tiniest transparent GIF possible at **36** bytes. (Again,
+like Paul, do let me know if you can make one smaller!).
-Another interesting tidbit gleaned from this experimentation is that the transparent image can be any pixel size up to 65535 square and still remain at the 36 bytes. Quite what one would do with a 4,294,836,225 pixel transparent GIF, I'm not sure.
+Another interesting tidbit gleaned from this experimentation is that the
+transparent image can be any pixel size up to 65535 square and still remain
+at the 36 bytes. Quite what one would do with a 4,294,836,225 pixel transparent
+GIF, I'm not sure.
-If, for any reason, you want to get a hand on those 36 little bytes, here they are in two formats:
-<ol>
- <li><strong>Hex Bytes</strong>: <pre>47 49 46 38 39 61 01 00 01
-00 00 00 00 21 f9 04 01 00
-00 00 00 2c 00 00 00 00 01
-00 01 00 00 01 01 01 00 3b</pre></li>
- <li><strong>GIF Image</strong>: <a href="http://cowburn.info/files/1px-trans.gif">download here</a> (it's not much to look at!)</li>
-</ol>
+If, for any reason, you want to get a hand on those 36 little bytes, here they
+are in two formats:
-Anyhow, that's enough frivolity for a Sunday evening. Back to watching the wildlife documentary on TV. :)
+1. **Hex Bytes**:
+
+ 47 49 46 38 39 61 01 00 01
+ 00 00 00 00 21 f9 04 01 00
+ 00 00 00 2c 00 00 00 00 01
+ 00 01 00 00 01 01 01 00 3b
+
+1. **GIF Image**: [download here][file] (it's not much to look at!)
+
+
+Anyhow, that's enough frivolity for a Sunday evening. Back to watching the
+wildlife documentary on TV. :)
+
+ [bonser]: http://blog.paulbonser.com/2009/03/15/the-tiniest-gif-ever/
+ [gif]: http://www.w3.org/Graphics/GIF/spec-gif89a.txt
+ [file]: /public/files/1px-trans.gif
View
52 _posts/2009-04-01-php-array-mode.markdown
@@ -3,10 +3,16 @@ layout: post
title: Modal value(s) in PHP
excerpt: Creating a function to find the most common value(s) in an array.
---
-I was browsing around the <a href="http://bryanculver.com/" rel="external friend">website</a> of someone on <a href="http://webetalk.com" rel="external">IRC</a> and found that they had written a function to determine the mode of an array of values. <a href="http://bryanculver.com/find-mode/" rel="external friend">The function</a> seems a little convoluted so in a spare 15 minutes I decided to re-implement it, take care of some of its caveats and make a quick blog post, the one you see here.<a id="more"></a><a id="more-156"></a>
+I was browsing around the [website][bryan] of someone on [IRC][irc] and found
+that they had written a function to determine the mode of an array of values.
+[The function][bryan-article] seems a little convoluted so in a spare
+15 minutes I decided to re-implement it, take care of some of its caveats
+and make a quick blog post, the one you see here.
-<h3>The function: array_mode</h3>
-<pre lang="php">/**
+## The function: array_mode
+
+{% highlight php startinline %}
+/**
* Returns the mode value(s) for an array.
*
* @param array The array of values to determine the mode.
@@ -28,11 +34,16 @@ function array_mode(array $set)
// Multiple modal values
return $modes;
-}</pre>
+}
+{% endhighlight %}
+
+## Examples
+
+Hopefully how this is used should be obvious, since it's such a simple function.
+If you really must have something to copy-and-paste:
-<h3>Examples</h3>
-Hopefully how this is used should be obvious, since it's such a simple function. If you really must have something to copy-and-paste:
-<pre lang="php">$single_mode = array('a', 'b', 'a', 'b', 'c', 'a');
+{% highlight php startinline %}
+$single_mode = array('a', 'b', 'a', 'b', 'c', 'a');
$multi_mode = array(0, 0, 2, 2, 1, 1, 3);
$no_mode = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
@@ -40,11 +51,28 @@ var_dump(
array_mode($single_mode), // "a"
array_mode($multi_mode), // array(0,2,1)
array_mode($no_mode) // FALSE
-);</pre>
+);
+{% endhighlight %}
+
+## Quick discussion
+
+The actual process is fairly simple but note that it needs PHP 5.1 or higher
+(because we use type hinting in the function definition) which shouldn't be an
+issue since PHP 5.2.9 is the current stable release and if you're still stuck
+with PHP 4, well I'm sorry. <ins datetime="2009-04-01T19:16:00+0100">[Update:
+Bryan posted up a [PHP4-compatible version][bryan-article] if you need it]</ins>
-<h3>Quick discussion</h3>
-The actual process is fairly simple but note that it needs PHP 5.1 or higher (because we use type hinting in the function definition) which shouldn't be an issue since PHP 5.2.9 is the current stable release and if you're still stuck with PHP 4, well I'm sorry. <ins datetime="2009-04-01T19:16:00+0100">[Update: Bryan posted up a <a href="http://bryanculver.com/find-mode/" rel="external">PHP4-compatible version</a> if you need it]</ins>
+The magic is really taken care of by the first three lines inside the function
+which counts how often any value occurs within the supplied array, then grabs
+the ones which occur most often (the mode). The rest of the function just takes
+care of the return values given different circumstances: if the is no mode
+(all values occur once only), just one mode (that value is returned) or
+multiple modal values (an array of these values is returned).
-The magic is really taken care of by the first three lines inside the function which counts how often any value occurs within the supplied array, then grabs the ones which occur most often (the mode<ins datetime="2010-07-1T07:53:00+0000">; <a href="#comment-59895">thanks Rob</a></ins>). The rest of the function just takes care of the return values given different circumstances: if the is no mode (all values occur once only), just one mode (that value is returned) or multiple modal values (an array of these values is returned).
+In the case that there are multiple modal values, the returned array will have
+the values in the order in which they were assigned in the original array.
+It's trivial to sort them, if that's what you need.
-In the case that there are multiple modal values, the returned array will have the values in the order in which they were assigned in the original array. It's trivial to sort them, if that's what you need.
+ [bryan]: http://bryanculver.com/
+ [irc]: http://webetalk.com
+ [bryan-article]: http://bryanculver.com/find-mode/
View
11 _posts/2009-06-12-php-doc.markdown
@@ -3,4 +3,13 @@ layout: post
title: Joined the PHP Documentation Team
excerpt: Write The F***ing Manual!
---
-<img src="http://cowburn.info/wp-content/uploads/2009/06/php-med-trans1.png" alt="PHP logo" title="PHP logo" width="95" height="51" class="alignleft size-full wp-image-175" /> This is just a very short update to announce quietly that I recently joined the team of folks working on the <a href="http://php.net/docs" title="PHP Documentation">PHP documentation</a>. It's another step towards giving a little something back to the PHP community by adding to and updating the constantly evolving docs which have helped me along for so many years. Incidentally, my first commit was too large to be sent out to the mailing list tracking the changes to the documentation. Oops!
+![PHP logo](/public/files/php-med-trans1.png "PHP logo")
+
+This is just a very short update to announce quietly that I recently joined
+the team of folks working on the [PHP documentation][docs]. It's another
+step towards giving a little something back to the PHP community by adding
+to and updating the constantly evolving docs which have helped me along for
+so many years. Incidentally, my first commit was too large to be sent out to
+the mailing list tracking the changes to the documentation. Oops!
+
+ [docs]: http://php.net/docs "PHP Documentation"
View
68 _posts/2009-06-14-parsing-dates-with-datetime.markdown
@@ -3,43 +3,79 @@ layout: post
title: Parsing Dates with DateTime
excerpt: What to do when <code>strtotime()</code> misbehaves.
---
-This post comes on the back of a number of forum posts I've seen floating around where the Original Poster (OP) asks a question along the lines of, "<q>I have a date in dd/mm/yyy format, how can I work with it?</q>"
+This post comes on the back of a number of forum posts I've seen floating around
+where the Original Poster (OP) asks a question along the lines of,
+"<q>I have a date in dd/mm/yyy format, how can I work with it?</q>"
-The problem is that the most common way of parsing strings into a more usable format (Unix timestamp) is to use <code>strtotime()</code>. However, this function does not like <samp>dd/mm/yyyy</samp> formatted strings and will at best parse the string as <samp>mm/dd/yyyy</samp> and at worst return <var>FALSE</var> (if it could not parse the date string as mm/dd/yyyy).<a id="more"></a><a id="more-182"></a>
+The problem is that the most common way of parsing strings into a more usable
+format (Unix timestamp) is to use `strtotime()`. However, this function does
+not like <samp>dd/mm/yyyy</samp> formatted strings and will at best parse the
+string as <samp>mm/dd/yyyy</samp> and at worst return <var>FALSE</var>
+(if it could not parse the date string as mm/dd/yyyy).
-<h3>Quick workaround</h3>
-One quick thing that works, and I've advocated in forum posts before, is to provide a date string in the format <samp>dd-mm-yyyy</samp>. Note that the date parts are in the same order, just the separator has changed from a forward slash (<code>/</code>) to a hyphen (<code>-</code>). A date formatted in this way will be happily parsed by <code>strtotime</code>. For example:
+## Quick workaround
-<pre lang="php">
+One quick thing that works, and I've advocated in forum posts before, is to
+provide a date string in the format <samp>dd-mm-yyyy</samp>. Note that the
+date parts are in the same order, just the separator has changed from a forward
+slash (`/`) to a hyphen (`-`). A date formatted in this way will be happily
+parsed by `strtotime()`. For example:
+
+{% highlight php startinline %}
date_default_timezone_set('UTC');
$date = '14/06/2009'; // dd/mm/yyyy
$date = str_replace('/', '-', $date); // dd-mm-yyyy
echo date('r', strtotime($date));
// Sun, 14 Jun 2009 00:00:00 +0000
-</pre>
+{% endhighlight %}
+
+## Using DateTime
-<h3>Using DateTime</h3>
-As of PHP 5.2.0 (and experimentally in 5.1.x) we have also had the ability to play with dates and times using the built-in <code>DateTime</code> extension <span class="aside">(Aside: the <code>date_default_timezone_set</code> function used above comes from this extension)</span>. To repeat the above but in <code>DateTime</code> form:
+As of PHP 5.2.0 (and experimentally in 5.1.x) we have also had the ability to
+play with dates and times using the built-in `DateTime` extension (Aside: the
+`date_default_timezone_set` function used above comes from this extension).
+To repeat the above but in `DateTime` form:
-<pre lang="php">
+{% highlight php startinline %}
$date = '14/06/2009'; // dd/mm/yyyy
$date = str_replace('/', '-', $date); // dd-mm-yyyy
$date = new DateTime($date, new DateTimeZone('UTC'));
echo $date->format('r');
// Sun, 14 Jun 2009 00:00:00 +0000
-</pre>
+{% endhighlight %}
-<h3>Help Coming!</h3>
-I'm sure that you'll agree, the above is hardly a perfect solution to the problem (but is a sufficient workaround for now). However help is at hand. As of <strong>PHP 5.3.0</strong> we will be able to make use of a new static method on the <code>DateTime</code> class. This method is <code>DateTime::createFromFormat</code> which requires two arguments; a string specifying the format which the date string has (as used by the <code>date</code> function), and the date string itself (there is also a third, optional, argument for the timezone to be used).
+## Help Coming!
+
+I'm sure that you'll agree, the above is hardly a perfect solution to the
+problem (but is a sufficient workaround for now). However help is at hand.
+As of **PHP 5.3.0** we will be able to make use of a new static method on the
+`DateTime` class. This method is `DateTime::createFromFormat()` which requires
+two arguments; a string specifying the format which the date string has (as used
+by the `date()` function), and the date string itself (there is also a third,
+optional, argument for the timezone to be used).
An example of its use, analogous to the snippets above, would be:
-<pre lang="php">
+
+{% highlight php startinline %}
$date = DateTime::createFromFormat('d/m/Y', '14/06/2009', new DateTimeZone('UTC'));
$date->setTime(0,0,0);
echo $date->format('r');
// Sun, 14 Jun 2009 00:00:00 +0000
-</pre>
+{% endhighlight %}
-<span class="aside">Aside: For my installation (PHP 5.3.0RC3) this method does not parse the date string as midnight, as the other code snippets do, but will use current time! This is why the <code>setTime</code> method (available as of 5.2.0) is used, to force the time to be midnight (arguments are <var>hour</var>, <var>minute</var>, <var>second</var>). <em>Edit:</em> One could instead use the <code>!</code> within the format string like <code>!d/m/Y</code>, since the time portion is missing it will substitute the Unix epoch's time (midnight) in its place. See the manual for details of <code>!</code>.</span>
+<small>
+Aside: For my installation (PHP 5.3.0RC3) this method does not parse the
+date string as midnight, as the other code snippets do, but will use current
+time! This is why the `setTime()` method (available as of 5.2.0) is used, to
+force the time to be midnight (arguments are <var>hour</var>, <var>minute</var>,
+<var>second</var>). _Edit:_ One could instead use the `!` within the format
+string like `!d/m/Y`, since the time portion is missing it will substitute the
+Unix epoch's time (midnight) in its place. See the manual for details of `!`.
+</small>
-Just to wrap things up, the <code>DateTime::createFromFormat</code> should help considerably towards parsing previously ambiguous date strings into forms that can be manipulated and at least will get around the string manipulation being offered as a solution right now. If you're still stuck playing around with the date string, at least you know that <samp>dd-mm-yyyy</samp> will be parsed as you want.
+Just to wrap things up, the `DateTime::createFromFormat()` should help
+considerably towards parsing previously ambiguous date strings into forms that
+can be manipulated and at least will get around the string manipulation being
+offered as a solution right now. If you're still stuck playing around with the
+date string, at least you know that <samp>dd-mm-yyyy</samp> will be parsed
+as you want.
View
63 _posts/2009-06-15-xpath-css-class.markdown
@@ -3,28 +3,61 @@ layout: post
title: XPath for CSS classes
excerpt: How to match a specific CSS class name in an XPath query.
---
-I was playing around with <a href="http://developer.yahoo.com/yql/" title="Yahoo! Query Language">YQL</a> today and was scraping a HTML document (no details, that's not the point of this blog entry). Part of the processes meant that I needed to check for a specific CSS class attached to some elements.
+I was playing around with [YQL][yql] today and was scraping a HTML document
+(no details, that's not the point of this blog entry). Part of the processes
+meant that I needed to check for a specific CSS class attached to some elements.
-Easy enough, XPath contains (pardon the pun, see later) some nifty functions which can act on nodes and their values to be used in conditional checks like I needed. I've been using the technique outlined in this post for a very long while (usually with XPath in PHP) and originally stumbled upon the basic idea from <a href="http://plasmasturm.org/log/444/">How to map CSS selectors to XPath queries</a> (Thanks ever so much!) Today's use of it prompted this blog post. <a id="more"></a><a id="more-203"></a>
+Easy enough, XPath contains (pardon the pun, see later) some nifty functions
+which can act on nodes and their values to be used in conditional checks like
+I needed. I've been using the technique outlined in this post for a very long
+while (usually with XPath in PHP) and originally stumbled upon the basic idea
+from [How to map CSS selectors to XPath queries][plasmasturm] (Thanks ever so
+much!) Today's use of it prompted this blog post.
-For example, to grab any <code>li</code> elements with a class of <var>active</var> (and only that one class) out of the document it would be easy enough to use:
-<pre lang="xpath">
+For example, to grab any `li` elements with a class of <var>active</var> (and
+only that one class) out of the document it would be easy enough to use:
+
+```
//li[@class="active"]
-</pre>
+```
+
+Now, as I said that will only grab the list items which have that specific
+class like `<li class="active">`. What if there is more than one class
+in there, ala `<li class="hot active">`? We could use the XPath function
+`contains()` which looks to see if a string contains another string but that
+would cause problems (e.g. searching for "a" in conjunction with classes like
+"active", "nav", etc. would result in false positives).
-Now, as I said that will only grab the list items which have that specific class like <code>&lt;li class="active"&gt;</code>. What if there is more than one class in there, ala <code>&lt;li class="hot active"&gt;</code>? We could use the XPath function <code>contains</code> which looks to see if a string contains another string but that would cause problems (e.g. searching for "a" in conjunction with classes like "active", "nav", etc. would result in false positives).
+To match any list item with a classes which contains the letter "a" can be
+sought with:
-To match any list item with a classes which contains the letter "a" can be sought with:
-<pre lang="xpath">
+```
//li[contains(@class, "a")]
-</pre>
+```
+
+Nearly there, now to work out how to not match false positives. To do this,
+we can look for `[space]a[space]` with a slightly modified class string
+(classes at the start/end of the string wouldn't normally have spaces
+before/after respectively). Whilst we're at it, we can _normalize_ the spaces
+in the class string which converts any number of spaces, tabs, etc. characters
+into just a single space.
-Nearly there, now to work out how to not match false positives. To do this, we can look for "<code>[space]a[space]</code>" with a slightly modified class string (classes at the start/end of the string wouldn't normally have spaces before/after respectively). Whilst we're at it, we can <em>normalize</em> the spaces in the class string which converts any number of spaces, tabs, etc. characters into just a single space.
+So, to properly get at a class name of <var>active</var> for all list items,
+regardless of its position in the class string, the following XPath query
+can be used.
-So, to properly get at a class name of "<var>active</var>" for all list items, regardless of its position in the class string, the following XPath query can be used.
-<pre lang="xpath">
+```
//li[contains(concat(" ", normalize-space(@class), " "), " active ")]
-</pre>
-<span class="aside">Note: there are single spaces in the first and last arguments for <code>concat</code>, and on either side of the word <code>active</code></span>.
+```
+
+<small>
+Note: there are single spaces in the first and last arguments for `concat`,
+and on either side of the word `active`.
+</small>
+
+Just as an observation, the comparable CSS selector to do this would be
+`li[class~="active"]` (or the more usual `li.active`) which would be awesome
+to use if XPath decided to implement a similar syntax.
-Just as an observation, the comparable CSS selector to do this would be <code>li[class~="active"]</code> (or the more usual <code>li.active</code>) which would be awesome to use if XPath decided to implement a similar syntax.
+ [yql]: http://developer.yahoo.com/yql/ "Yahoo! Query Language"
+ [plasmasturm]: http://plasmasturm.org/log/444/
View
108 _posts/2009-07-08-anonymous-closures.markdown
@@ -3,12 +3,22 @@ layout: post
title: Anonymous Functions and Closures (as of PHP 5.3)
excerpt: A brief introduction to anonymous function literals and closures.
---
-There has been much discussion, especially of late considering the release of PHP 5.3, on the subject of anonymous functions and closures (both terms appear to be used interchangeably in the <a href="http://php.net/closures" title="Closures in the PHP Manual">documentation</a>). They are not the same, though many folks are introduced to them at the same time.<a id="more"></a><a id="more-234"></a>
+There has been much discussion, especially of late considering the release of
+PHP 5.3, on the subject of anonymous functions and closures (both terms appear
+to be used interchangeably in the [documentation][docs]). They are not the
+same, though many folks are introduced to them at the same time.
-<h3>Anonymous Functions</h3>
-Put plainly, an anonymous function is a function without a name. That's all, there's nothing magic or particularly technical about it. There are a few ways to create an anonymous function in PHP; up until PHP 5.3 came around the usual way was to use <a href="http://php.net/create_function" title="create_function documentation on php.net"><code>create_function</code></a> (see <a href="#fig1" title="View figure 1: Anonymous function with create_function">fig. 1</a>) which takes a couple of arguments as strings and spits out a function, in PHP 5.3 we're allowed to create anonymous functions looking much more like normal function definitions (see <a href="#fig2" title="View figure 2: Anonymous function in PHP 5.3">fig. 2</a>).
+## Anonymous Functions
-<h4 id="fig1">Fig. 1: Anonymous function with create_function</h4>
+Put plainly, an anonymous function is a function without a name. That's all,
+there's nothing magic or particularly technical about it. There are a few ways
+to create an anonymous function in PHP; up until PHP 5.3 came around the usual
+way was to use [create_function()][create_function] (see [fig. 1][fig1]) which
+takes a couple of arguments as strings and spits out a function, in PHP 5.3
+we're allowed to create anonymous functions looking much more like normal
+function definitions (see [fig. 2][fig2]).
+
+### <span id="fig1"></span>Fig. 1: Anonymous function with create_function
{% highlight php %}
<?php
@@ -17,46 +27,69 @@ echo $square(2); // 4
?>
{% endhighlight %}
-<h4 id="fig2">Fig 2: Anonymous function as of PHP 5.3</h4>
-<pre lang="PHP">
+### <span id="fig2"></span>Fig 2: Anonymous function as of PHP 5.3
+
+{% highlight php %}
<?php
$square = function($x) {
return $x * $x;
};
echo $square(2); // 4
?>
-</pre>
+{% endhighlight %}
+
+I hope you'll agree that the latter is a much nicer way (visually) of defining
+an anonymous function, quite apart from the more logical and performance-related
+(see [comment #4][fabpot_comment]) aspects of using it.
+
+## Closures
+
+A closure is a (anonymous) function that is aware of its context. For all
+intents and purposes, think of them being anonymous functions which know about
+some variables which weren't defined within them. In geeky language, they are
+functions which close over (hence "closure") free variables, the latter being
+variables which are not local nor arguments to the function. It is easier to
+see with an example, I think.
-I hope you'll agree that the latter is a much nicer way (visually) of defining an anonymous function, quite apart from the more logical and performance-related (see <a href="http://fabien.potencier.org/article/17/on-php-5-3-lambda-functions-and-closures#comments" title="Comments on 'On PHP 5.3, Lambda Functions, and Closures'">comment #4</a>) aspects of using it.
+### <span id="fig3"></span>Without Closure
-<h3>Closures</h3>
-A closure is a (anonymous) function that is aware of its context. For all intents and purposes, think of them being anonymous functions which know about some variables which weren't defined within them. In geeky language, they are functions which close over (hence "closure") free variables, the latter being variables which are not local nor arguments to the function. It is easier to see with an example, I think.
+Lets say that we need a function to add three to a number (overly basic, I
+know). That's easy.
-<h4 id="fig3">Without Closure</h4>
-Lets say that we need a function to add three to a number (overly basic, I know). That's easy.
-<pre lang="PHP">
+{% highlight php %}
<?php
$add_3 = function($x) {
return $x + 3;
};
echo $add_3(10); // 13
?>
-</pre>
-Now if we wanted another function to behave similarly but instead it should add 4 to the supplied number, we could just as easily create a new anonymous function to do the job.
-<pre lang="PHP">
+{% endhighlight %}
+
+Now if we wanted another function to behave similarly but instead it should add
+4 to the supplied number, we could just as easily create a new anonymous
+function to do the job.
+
+{% highlight php %}
<?php
$add_4 = function($x) {
return $x + 4;
};
echo $add_4(10); // 14
?>
-</pre>
+{% endhighlight %}
-If, however, you wanted to do that for a series of different additions then things could get very repetitive, very quickly! If only we could dynamically create an anonymous function to do what we wanted: enter the closure.
+If, however, you wanted to do that for a series of different additions then
+things could get very repetitive, very quickly! If only we could dynamically
+create an anonymous function to do what we wanted: enter the closure.
-<h4 id="fig4">With Closure</h4>
-We can define an anonymous function (it needn't be anonymous but lets keep on theme) which returns anonymous function based on arguments supplied to it. Remember our definition of a closure above, specifically making use of 'free' variables, that is what our <code>$value_to_add</code> is in the example below.
-<pre lang="PHP">
+### <span id="fig4"></span>With Closure
+
+We can define an anonymous function (it needn't be anonymous but lets keep on
+theme) which returns anonymous function based on arguments supplied to it.
+Remember our definition of a closure above, specifically making use of 'free'
+variables, that is what our `$value_to_add` is in the example below.
+
+{% highlight php %}
<?php
$add = function($value_to_add) {
return function ($x) use ($value_to_add) {
@@ -70,13 +103,18 @@ $add_4 = $add(4);
echo $add_3(10); // 13
echo $add_4(10); // 14
?>
-</pre>
+{% endhighlight %}
+
+## A more practical example
+
+As fun as silly adding examples are, there will be undoubtedly someone who has
+been reading everything above (good job getting this far!) and cannot see a
+practical use for all of this. Since [le Tour de France][letour] is on, let's
+have a play on words and have an example on cycling (over a series of values).
-<h3>A more practical example</h3>
-As fun as silly adding examples are, there will be undoubtedly someone who has been reading everything above (good job getting this far!) and cannot see a practical use for all of this. Since <a href="http://www.letour.fr/" title="Site officiel du tour de France">le Tour de France</a> is on, lets have a play on words and have an example on cycling (over a series of values).
+### <span id="fig5"></span>Cycling with Closures
-<h4 id="fig5">Cycling with Closures</h4>
-<pre lang="PHP">
+{% highlight php %}
<?php
// Cycle factory: takes a series of arguments
// for the closure to cycle over.
@@ -110,11 +148,11 @@ $items = array('apple', 'banana', 'cherry', 'date', 'elderberry', 'figs');
<li class="<?php echo $class() ?>"><?php echo $item ?> are <?php echo $taste() ?></li>
<?php endforeach ?>
</ul>
-
-</pre>
+{% endhighlight %}
That example would provide the following output:
-<pre lang="html4strict">
+
+{% highlight html %}
<ul>
<li class="odd">apples are vile</li>
<li class="even">bananas are yummy</li>
@@ -123,6 +161,14 @@ That example would provide the following output:
<li class="odd">elderberries are yummy</li>
<li class="even">figs are delicious</li>
</ul>
-</pre>
+{% endhighlight %}
+
+Well, it's a little bit more practical anyway! Have you been playing with
+closures and/or anonymous functions too?
-Well, it's a little bit more practical anyway! Have you been playing with closures and/or anonymous functions too?
+ [docs]: http://php.net/closures "Closures in the PHP Manual"
+ [create_function]: http://php.net/create_function "create_function documentation on php.net"
+ [fig1]: #fig1 "View figure 1: Anonymous function with create_function"
+ [fig2]: #fig2 "View figure 2: Anonymous function in PHP 5.3"
+ [fabpot_comment]: http://fabien.potencier.org/article/17/on-php-5-3-lambda-functions-and-closures#comments ""Comments on 'On PHP 5.3, Lambda Functions, and Closures'""
+ [letour]: http://www.letour.fr/ "Site officiel du tour de France"
View
36 _posts/2009-09-25-infiniteiterator.markdown
@@ -6,15 +6,32 @@ excerpt: 'Introducing the <a href="http://php.net/InfiniteIterator" title="PHP
<a href="http://php.net/spl" title="Standard PHP Library">Standard PHP Library</a>
(SPL).'
---
-In an article back in July ([Anonymous Functions and Closures (as of PHP 5.3)](http://cowburn.info/2009/07/08/anonymous-closures/ "Read Anonymous Functions and Closures (as of PHP 5.3)")), I gave [an example](http://cowburn.info/2009/07/08/anonymous-closures/#fig5 "See example: Cycling with Closures") of looping over a series of values repeatedly. Whilst that example does the job (and introduces the concept of closures) it's hardly the most convenient method of repeatedly iterating over a series of values. Introducing the [`InfiniteIterator`](http://php.net/InfiniteIterator "PHP Manual: InfiniteIterator") which is part of the [Standard PHP Library](http://php.net/spl "Standard PHP Library") (SPL).
+In an article back in July ([Anonymous Functions and Closures (as of PHP 5.3)][closures]),
+I gave [an example][fig5] of looping over a series of values repeatedly. Whilst
+that example does the job (and introduces the concept of closures) it's hardly
+he most convenient method of repeatedly iterating over a series of values.
+Introducing the [`InfiniteIterator`][docs] which is part of the
+[Standard PHP Library][spl].
-On the plus side, for those who have yet to take the plunge into using PHP 5.3, this iterator has been part of the core of PHP as of 5.1.0 so there is a much greater chance of actually being able to use it right now. Bear in mind that the SPL is supposed to work together with its component parts so if [iterators](http://php.net/iterator "PHP: Object Iteration") are a foreign concept, some of this post might be a little unclear but it is not the purpose of this post to outline iterators in PHP.
+On the plus side, for those who have yet to take the plunge into using PHP 5.3,
+this iterator has been part of the core of PHP as of 5.1.0 so there is a much
+greater chance of actually being able to use it right now. Bear in mind that
+the SPL is supposed to work together with its component parts so if
+[iterators][iterators] are a foreign concept, some of this post might be a
+little unclear but it is not the purpose of this post to outline iterators
+in PHP.
-As eluded to above, the `InfiniteIterator` comes in useful when you have an existing `Iterator` (anything that implements that interface; a directory listing (`DirectoryIterator`), a file (`SplFileObject`), an array (with `ArrayIterator`), and so on) and wish to iterate over its contents again and again.
+As eluded to above, the `InfiniteIterator` comes in useful when you have an
+existing `Iterator` (anything that implements that interface; a directory
+listing (`DirectoryIterator`), a file (`SplFileObject`), an array
+(with `ArrayIterator`), and so on) and wish to iterate over its contents
+again and again.
### An `InfiniteIterator` Example
-Here is a basic example that I wrote for the [documentation](http://php.net/InfiniteIterator.construct "PHP Manual: InfiniteIterator::__construct"). Note that a [`LimitIterator`](http://php.net/LimitIterator "The LimitIterator class") is used to restrict the values which are iterated over (otherwise the loop would go on forever!).
+Here is a basic example that I wrote for the [documentation][construct]. Note
+that a [`LimitIterator`][limititerator] is used to restrict the values which
+are iterated over (otherwise the loop would go on forever!).
```php
<?php
@@ -40,4 +57,13 @@ dog
cat
```
-Can you think of any more useful instances where the `InfiniteIterator` might come in useful?
+Can you think of any more useful instances where the `InfiniteIterator` might
+come in useful?
+
+ [closures]: http://cowburn.info/2009/07/08/anonymous-closures/ "Read Anonymous Functions and Closures (as of PHP 5.3)"
+ [fig5]: http://cowburn.info/2009/07/08/anonymous-closures/#fig5 "See example: Cycling with Closures"
+ [docs]: http://php.net/InfiniteIterator "PHP Manual: InfiniteIterator"
+ [spl]: http://php.net/spl "Standard PHP Library"
+ [iterators]: http://php.net/iterator "PHP: Object Iteration"
+ [construct]: http://php.net/InfiniteIterator.construct "PHP Manual: InfiniteIterator::__construct"
+ [limititerator]: http://php.net/LimitIterator "The LimitIterator class"
View
114 _posts/2009-10-23-php-funcs-xpath.markdown
@@ -5,23 +5,31 @@ excerpt: The <code>DOMXPath::registerPHPFunctions()</code> method is available a
of PHP 5.3.0 and allows the use of PHP functions (and static methods)
within XPath queries to complement the normal set of XPath functions.
---
-Disclaimer: this article expects familiarity with using the DOM<sup><a href="#fn1" title="footnote 1">1</a></sup> extension and XPath<sup><a href="#fn2" title="footnote 2">2</a></sup> expressions.
+Disclaimer: this article expects familiarity with using the DOM<sup>[1][fn1]</sup>
+extension and XPath<sup>[2][fn2]</sup> expressions.
-The (<del datetime="2009-10-26T14:15:44Z">currently undocumented</del><ins datetime="2009-10-26T14:15:44Z">now documented</ins><sup><a href="#fn3" title="footnote 3">3</a></sup>) <code>DOMXPath::registerPHPFunctions</code> method is available as of PHP 5.3.0 (it was added to the code base back in December 2006) and allows the use of PHP functions (and static methods) within XPath queries to complement the normal set of XPath functions<sup><a href="#fn2" title="footnote 2">2</a></sup>.<a id="more"></a><a id="more-336"></a>
+The (<del datetime="2009-10-26T14:15:44Z">currently undocumented</del>
+<ins datetime="2009-10-26T14:15:44Z">now documented</ins><sup>[3][fn3]</sup>)
+`DOMXPath::registerPHPFunctions()` method is available as of PHP 5.3.0 (it was
+added to the code base back in December 2006) and allows the use of PHP
+functions (and static methods) within XPath queries to complement the normal
+set of XPath functions<sup>[2][fn2]</sup>.
## Description
-<code>void DOMXPath::registerPHPFunctions ([ string|array <var>$restrict</var>] )</code>
+`void DOMXPath::registerPHPFunctions ([ string|array <var>$restrict</var>] )`
Enables the use of PHP functions as XPath functions.
## Parameters
<dl>
-<dt>restrict</dt>
-<dd>
-Use this parameter to only allow certain functions to be called from XPath; it can be either a string (a function name) or an array of function names.
-</dd>
+ <dt>restrict</dt>
+ <dd>
+ Use this parameter to only allow certain functions to be called from
+ XPath; it can be either a string (a function name) or an array of
+ function names.
+ </dd>
</dl>
## Return Values
@@ -30,7 +38,8 @@ No value is returned.
## Examples
-**Note:** The following examples load a sample XML document called <kbd>book.xml</kbd> with the following contents:
+**Note:** The following examples load a sample XML document called
+<kbd>book.xml</kbd> with the following contents:
{% highlight xml %}
<?xml version="1.0" encoding="UTF-8"?>
@@ -51,13 +60,30 @@ No value is returned.
</books>
{% endhighlight %}
-<h3 id="ex1">Example #1: Call a PHP function in XPath with `php:functionString`</h3>
-
-This example demonstrates the basic use of `DOMXPath::registerPHPFunctions` by replicating the `substring` XPath function. The first thing that needs to be done is to register the <samp>php</samp> namespace with the associated URI <samp>http://php.net/xpath</samp>. Don't question it, it just needs to be done!
-
-Next, we call `DOMXPath::registerPHPFunctions` on our object. If no arguments are used, as in this example, then the range of functions allowed to be called is not restricted—you can call any<sup><a href="#fn4" title="footnote 4">4</a></sup> function from XPath. I would always advise restricting the functions which can be called, see <a href="#ex2" title="Example 2">example 2</a>.
-
-Within our XPath query, we use `php:functionString` which allows us to name a function and provide some parameters (or indeed, no parameters) to be passed to that function. There are two flavours which can be used here: `php:functionString` which passes an XML node/attribute as a string and `php:function` (see <a href="#ex3" title="Example 3">example 3</a>) which passes an array of XML node/attribute objects (in `DOMElement` / `DOMAttr` / etc. form) to the function . In this example the PHP function <a href="http://php.net/substr">`substr`</a> is called, passing along the book's title (in string form), an offset of <samp>0</samp> and length of <samp>3</samp>. This returns the first 3 characters of the book's title which is then compared to the string <kbd>PHP</kbd> in order to filter our list of books down to those having titles starting with <kbd>PHP</kbd>.
+### <span id="ex1">Example #1: Call a PHP function in XPath with `php:functionString()`</span>
+
+This example demonstrates the basic use of `DOMXPath::registerPHPFunctions()`
+by replicating the `substring()` XPath function. The first thing that needs to
+be done is to register the <samp>php</samp> namespace with the associated URI
+<samp>http://php.net/xpath</samp>. Don't question it, it just needs to be done!
+
+Next, we call `DOMXPath::registerPHPFunctions()` on our object. If no arguments
+are used, as in this example, then the range of functions allowed to be called
+is not restricted—you can call any<sup>[4][fn4]</sup> function from XPath. I
+would always advise restricting the functions which can be called,
+see [example 2][ex2].
+
+Within our XPath query, we use `php:functionString()` which allows us to name
+a function and provide some parameters (or indeed, no parameters) to be passed
+to that function. There are two flavours which can be used here:
+`php:functionString()` which passes an XML node/attribute as a string and
+`php:function()` (see [example 3][ex3]) which passes an array of XML
+node/attribute objects (in `DOMElement` / `DOMAttr` / etc. form) to the
+function . In this example the PHP function [`substr()`][substr] is called,
+passing along the book's title (in string form), an offset of <samp>0</samp>
+and length of <samp>3</samp>. This returns the first 3 characters of the book's
+title which is then compared to the string <kbd>PHP</kbd> in order to filter our
+list of books down to those having titles starting with <kbd>PHP</kbd>.
{% highlight php %}
<?php
@@ -92,9 +118,16 @@ PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe
```
-<h3 id="ex2">Example #2: Restricting the functions available to XPath</h3>
+### <span id="ex2">Example #2: Restricting the functions available to XPath</span>
-To restrict the functions made available to XPath, provide either a string containing the name of the single function that you wish to allow or an array of strings containing function names as the <var>restrict</var> parameter (note: static methods can also be used, e.g. "<samp>Classname::method</samp>"). If functions were added with <var>restrict</var> and a function is called in XPath which is not one of them, an <var>E_WARNING</var> will be raised stating <samp>Not allowed to call handler '<var>function</var>()'</samp> (where <var>function</var> is the name of the function that cannot be called).
+To restrict the functions made available to XPath, provide either a string
+containing the name of the single function that you wish to allow or an array
+of strings containing function names as the <var>restrict</var> parameter
+(note: static methods can also be used, e.g. "<samp>Classname::method</samp>").
+If functions were added with <var>restrict</var> and a function is called in
+XPath which is not one of them, an <var>E_WARNING</var> will be raised stating
+<samp>Not allowed to call handler '<var>function</var>()'</samp> (where
+<var>function</var> is the name of the function that cannot be called).
{% highlight php %}
<?php
@@ -122,11 +155,15 @@ $fail = $xpath->evaluate('php:functionString("strtolower", //book[1]/title)');
The example will output something like:
<pre>PHP BASICS<br />
-<b>Warning</b>: DOMXPath::evaluate() [<a href='domxpath.evaluate'>domxpath.evaluate</a>]: Not allowed to call handler 'strtolower()'. in <b>example2.php</b> on line <b>18</b><br /></pre>
+<b>Warning</b>: DOMXPath::evaluate() [<a href='domxpath.evaluate'>domxpath.evaluate</a>]: Not allowed to call handler 'strtolower()'. in <b>example2.php</b> on line <b>18</b><br />
+</pre>
-<h3 id="ex3">Example #3: Passing DOM objects using `php:function`</h3>
+### <span id="ex3">Example #3: Passing DOM objects using `php:function()`</span>
-Up to now, the examples have both used `php:functionString`. As mentioned above, instead of passing a string value to the PHP function it is possible to pass along an array of DOM* objects to manipulate them as you please by using `php:function`.
+Up to now, the examples have both used `php:functionString()`. As mentioned
+above, instead of passing a string value to the PHP function it is possible
+to pass along an array of DOM* objects to manipulate them as you please by
+using `php:function()`.
{% highlight php %}
<?php
@@ -157,21 +194,38 @@ foreach ($books as $book) {
The example will output something like:
-<pre>Books with multiple authors:
+```
+Books with multiple authors:
PHP Basics
-</pre>
+```
### Summary
-Just to quickly summarise everything, here is a quick run-down. In PHP, make sure to register the <kbd>php</kbd> namespace (with the URI <kbd>http://php.net/xpath</kbd>) and then register your PHP functions (whether core, extensions or user-defined) or static methods with `DOMXPath::registerPHPFunctions`. In XPath, use `php:functionString` or `php:function` to call the PHP function.
+Just to quickly summarise everything, here is a quick run-down. In PHP, make
+sure to register the <kbd>php</kbd> namespace (with the URI
+<kbd>http://php.net/xpath</kbd>) and then register your PHP functions
+(whether core, extensions or user-defined) or static methods with
+`DOMXPath::registerPHPFunctions()`. In XPath, use `php:functionString()` or
+`php:function()` to call the PHP function.
-If you have made use of this feature, or want to know more, then do feel free to comment. Thanks for reading.
+If you have made use of this feature, or want to know more, then do feel free
+to comment. Thanks for reading.
#### Footnotes
-<ol>
-<li id="fn1"><a href="http://php.net/dom" title="PHP: DOM">http://php.net/dom</a></li>
-<li id="fn2"><a href="http://schlitt.info/opensource/blog/0704_xpath.html" title="XPath overview">http://schlitt.info/opensource/blog/0704_xpath.html</a>
-<li id="fn3">The documentation page, <del datetime="2009-10-26T14:15:44Z">when it gets written, will be</del><ins datetime="2009-10-26T14:15:44Z">is</ins> available at <a href="http://php.net/domxpath.registerphpfunctions" title="PHP: DOMXPath::registerPHPFunctions">http://php.net/domxpath.registerphpfunctions</a></li>
-<li id="fn4">In truth, some functions are not suitable such as those that return non-scalar values (and cannot be cast to one) which XPath will not understand.</li>
-</ol>
+1. <span id="fn1">[http://php.net/dom][dom]</span>
+1. <span id="fn2">[http://schlitt.info/opensource/blog/0704_xpath.html][schlitt]</span>
+1. <span id="fn3">The documentation page, is available at [http://php.net/domxpath.registerphpfunctions][register]</span>
+1. <span id="fn4">In truth, some functions are not suitable such as those that return non-scalar values (and cannot be cast to one) which XPath will not understand.</span>
+
+
+ [fn1]: #fn1 "footnote 1"
+ [fn2]: #fn2 "footnote 2"
+ [fn3]: #fn3 "footnote 3"
+ [fn4]: #fn4 "footnote 4"
+ [ex2]: #ex2 "example 2"
+ [ex3]: #ex3 "example 3"
+ [substr]: http://php.net/substr
+ [dom]: http://php.net/dom "PHP: DOM"
+ [schlitt]: http://schlitt.info/opensource/blog/0704_xpath.html "XPath overview"
+ [register]: http://php.net/domxpath.registerphpfunctions "PHP: DOMXPath::registerPHPFunctions"
View
BIN  public/files/1px-trans.gif
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  public/files/php-med-trans1.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Please sign in to comment.
Something went wrong with that request. Please try again.