Hey there, fellow dev! Ready to supercharge your PHP project with GitHub's API? You're in the right place. We'll be using the awesome knplabs/github-api package to make our lives easier. Let's dive in!
Before we start, make sure you've got:
First things first, let's get that package installed:
composer require knplabs/github-api php-http/guzzle6-adapter
Easy peasy, right?
Now, let's set up authentication. We'll use your personal access token:
$client = new \Github\Client(); $client->authenticate('your-token-here', null, \Github\AuthMethod::ACCESS_TOKEN);
You're authenticated! Time to make your first API call:
$user = $client->api('user')->show('your-username');
Boom! You've just fetched your user info. How cool is that?
Let's explore some common operations:
$repo = $client->api('repo')->show('username', 'repo-name');
$repos = $client->api('user')->repositories('username');
$issue = $client->api('issue')->create('username', 'repo-name', array('title' => 'Issue title', 'body' => 'Issue body'));
$prs = $client->api('pull_request')->all('username', 'repo-name');
GitHub's API uses pagination. Here's how to handle it:
$repos = $client->api('user')->repositories('username', 'all', 'page');
And don't forget about rate limits! Check your remaining requests:
$rateLimits = $client->api('rate_limit')->getResources();
Always be prepared for errors:
try { $repo = $client->api('repo')->show('username', 'repo-name'); } catch (\Github\Exception\RuntimeException $e) { echo 'Oops! ' . $e->getMessage(); }
Want to use a custom HTTP client? No problem:
$httpClient = new \Http\Adapter\Guzzle6\Client(); $client = new \Github\Client($httpClient);
And if you're using GitHub Enterprise, we've got you covered:
$client->setEnterpriseUrl('https://github.your-company.com');
Remember to cache your responses to be a good API citizen:
$cachePool = new \Cache\Adapter\Filesystem\FilesystemCachePool($filesystemAdapter); $client->addCache($cachePool);
And there you have it! You're now a GitHub API integration wizard. Remember, the official documentation is your best friend for more advanced features.
Now go forth and build something awesome! 🚀