I’m currently in the middle of rewriting the code-base of my company’s website and the CEO was extremely keen on keeping a plugin that fetches followers/likes from our social page’s for the “social proof” it adds to our site.
Me being stubborn was not willing to let go the fact that the plugin he’s currently using, as well as every alternative out there, either go extremely over the top in terms of functionality or take it upon themselves to bring in 6 different javascript libraries, FontAwesome along with 10 other icon fonts (customization!1!1!), and are overall terribly written.
Thus, SocialProof was born. SocialProof is a clean, fluent composer package allowing you to fetch followers from various social platform API’s with ease.
While it provides no caching out of the box leaving that up to the end-user, here is a quick and dirty example of doing this yourself with Sage 9 using the Transient API as a temporary store to keep our follower count up to date, and the Options API for keeping a backup in the event our API request fails due to invalidated credentials, API downtime, etc. For example sake, we are going to do this in our App
controller.
<?php
namespace App\Controllers;
use Sober\Controller\Controller;
use SocialProof\SocialProof;
class App extends Controller
{
/**
* Fetch our social followers from the provided platform.
* If our follower count is not available, we will attempt to fetch it.
*
* @param string $type
* @return integer
*/
public static function social ($type)
{
$key = '_social_followers';
$followers = get_transient($key) ?? [];
$cache = get_option($key, []);
if (!empty($followers[$type])) {
return $followers[$type];
}
$facebook = SocialProof::social()
->facebook()
->setUsername('example')
->setToken('xxxxxx')
->setDefault($cache['facebook'] ?? 0)
->get();
$twitter = SocialProof::social()
->twitter()
->setUsername('example')
->setConsumerKey('xxxxxx')
->setConsumerSecret('xxxxxx')
->setToken('xxxxxx')
->setTokenSecret('xxxxxx')
->setDefault($cache['twitter'] ?? 0)
->get();
$followers = [
'facebook' => $facebook,
'twitter' => $twitter
];
set_transient($key, $followers, 60*60*24);
update_option($key, $followers);
return $followers[$type];
}
}
This allows us to use {{ App::social('facebook') }}
from within’ our views to grab our count for Facebook. The example above is meerely just that, an example, and type checking as well as even putting your available platforms into an array to compare against $type
would more or less be necessary for real-world use.
Using ACF would come in handy for the ability to enable/toggle social platforms as well as store the API credentials that are passed to SocialProof.