April 21, 2010 2

Three Bitchin’ PHP Classes – Cache, Last.fm API, Time

CakePHP PHP

There’s nothing like the feeling that comes with typing a few lines in a PHP application and letting some included classes take care of the dirty work; you know, the filthy stuff like caching, calling the Last.fm API, purifying timestamps, and handling file uploads. (Dirty, right?)

All of the following PHP classes are “works in progress”, but hopefully each is mature enough to find its way into your code. Continue reading to view, download, and use each class.


Cache – Output & Object Caching

Though this class is old (three years), it does the trick, and quickly. Dragon Bosnjak wrote this gem, allowing for easy caching of webpage content into a directory (and filename) of your choosing.

Using Cache Class

Caching your web content is a breeze! Create a new Cache class by specifying a directory to store the cache file, and surround your webpage content in a while loop, like so:

$cache = new Cache("../cache/");

while ($cache->save("filename.cache", 30)) {
	// "30" is the number of seconds the content should remain cached.
	// Your cached content goes here...
 }

Download Cache

You can download and use this golden-nugget of love by visiting PHP Classes – perhaps the most poorly styled/organized website on the internet, but that’s another post entirely.


Last.fm API

If you have yet to discover the hotness of using “Magic Methods” in PHP, I suggest you read up on how to serve up a magic teapot of greatness using PHP5. These Magic Methods are exactly what I used to create this simple Last.fm API class. The result is the ability to quickly make almost any API call without having to continuously fiddle with API key variables, etc.

Using Last.fm API Class

After including the LastFm class file, you need to create a new instance of the LastFm() class.

// include class file
include_once('../inc/class.lastfm.php');

// initate LastFm class
$lastfm = new LastFm();
$lastfm->key = "1234567890"; // your LastFm API key

Then you can call your LastFm API action using the following conversion:

Let’s say we want to call User.getTopAlbums with the user argument set to bob and the period argument set to 3month:

$lastfm->user_getTopAlbums("user=iamkoa","period=3month");

The above PHP code will generate the following API call:


http://ws.audioscrobbler.com/2.0/?method=user.getTopAlbums&user=bob&period=3month&api_key=1234567890

Let The Class Parse Things For You…

The API call will return, for example, the following XML to Array:

Array
(
    [lfm] => Array
        (
            [attr] => Array
                (
                    [status] => ok
                )

            [recenttracks] => Array
                (
                    [attr] => Array
                        (
                            [user] => iamkoa
                            [page] => 1
                            [perPage] => 8
                            [totalPages] => 2777
                        )

                    [track] => Array
                        (
                            [0] => Array
                                (
                                    [artist] => Array
                                        (
                                            [value] => Black Eyed Peas
                                            [attr] => Array
                                                (
                                                    [mbid] => d5be5333-4171-427e-8e12-732087c6b78e
                                                )

                                        )
// etc...

To make any Last.fm API call, simply replace the . symbol with an _ symbol and include any arguments with a "var=bar" pattern. For example, here’s how to make a couple calls:

// call user.getWeeklyTrackChart
$lastfm->user_getWeeklyTrackChart("user=iamkoa");

// call group.getMembers
$lastfm->group_getMembers("group=groupName");

// etc...

Download Last.fm

Download and use the Last.fm PHP class. Please post any enhancements to the class here for others to use.


Time

Time is a bitch. It’s always against us. In the case of parsing a date string into a human-friendly string, it’s even more apparent that time sucks. Hopefully this Time class, though not entirely finished, will help with parsing dates.

Use it

It’s really, really simple to use:

$time = new Time();
echo $time->timeAgoInWords($date_string);

Depending upon when $date_string is relative to the current time, the above code might print one of the following:

"26 July, 2:45 PM", "Yesterday morning", "Today", "Last night", or "28 minutes ago", etc...

Editing the class is pretty simple, so I’ll let all you hackers dig into it for details.

Download Time

Download and use the Time PHP class. Please post any enhancements to the class here for others to use.

Tags: , , , , ,

2 Responses to “Three Bitchin’ PHP Classes – Cache, Last.fm API, Time”

  1. Michael says:

    Hey,

    For the Last.FM class I encountered a problem when dealing with arguments (user= or artist=) that have spaces in them. I solved the issue by doing the following:

    $lastfm->artist_getInfo(“artist=” . urlencode(“Test Artist”))

    which makes the text URL friendly since it is being called through a URL. However I’m sure there is a way to fix it in the class but I don’t understand the code you provided since it is a little above my head.

    Great article by the way! The last.fm and cache modules are very helpful.