Talking to GitHub with PHP

The Git-based project hosting service GitHub is certainly the belle of today's technology ball, having attracted more than 1 million registered users and amassed more than 2 million hosted projects in less than three years. On a personal note, during this time it has become an incredibly important part of my own professional activities, with GitHub playing a role in my client work, website development, management of source code associated with several of my books, and for keeping tabs on other cool projects.

The GitHub team does a pretty impressive job of responding to user feedback, adding and improving service features, all of which are blogged about in detail on the official blog, and itemized within the changelog. If keeping track of your various projects via your laptop isn't enough, a great iPhone app is also available. In addition, GitHub follows an approach embraced by many of today's successful software companies, allowing users to extend the service in new and interesting ways via a powerful and well-documented API.

GitHub High Scores and GitHub Badges are two examples of third-party services created using the GitHub API, which is capable of carrying out any task you might wish to perform via GitHub.com. With it you can create, edit and search repositories, learn more about fellow GitHub users, and manage repository issues.

Using the PHP GitHub API Library

A number of libraries are available for interacting with the API, among them php-github-api (PHP), py-github (Python), and github-api (JavaScript). Perhaps not surprisingly, all three of the aforementioned libraries are available via public GitHub repositories, meaning that getting started using one is as easy as cloning the project:

$ git clone https://github.com/ornicar/php-github-api

Once cloned, consider moving the lib/Github directory into your project's root directory, or move the Github directory into your existing libdirectory if one is already available. Next, include the library autoloader:

With the Github_Client class instantiated, it's time to begin interacting with GitHub!

Searching GitHub Repositories with PHP

Suppose you wanted to create a simple service that searched for all public GitHub repositories with a description containing a particular keyword, such as Zend. You can easily do so like this:

$repos = $github->getRepoApi()->search('Zend');

The $repos variable contains an array of multidimensional arrays, each of which contains useful information about the returned repositories such as the description, number of followers, and whether a download is available. Once retrieved, you can use PHP's relatively new anonymous function feature to sort the multidimensional arrays by a specific key value, such as the description, and output the results to the screen: