Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Last active December 2, 2017 17:27
Show Gist options
  • Save Shelob9/4b1b6797c543ace4311f240a68b5753d to your computer and use it in GitHub Desktop.
Save Shelob9/4b1b6797c543ace4311f240a68b5753d to your computer and use it in GitHub Desktop.
<?php
namespace App;
class WpApi {
protected static $url = 'https://calderaforms.com/wp-json/wp/v2/';
public static function getPost(int $id )
{
$url = self::$url . 'posts/' . $id;
return self::getJson( $url );
}
public static function getPosts( int $page )
{
$url = self::$url . '/posts?per_page=' . $page;
return collect( self::getJson( $url ) );
}
protected static function getJson( $url)
{
$response = file_get_contents($url, false);
return json_decode( $response );
}
}
<?php
namespace App;
use Illuminate\Support\Facades\Cache;
class WpApi {
protected static $url = 'https://calderaforms.com/wp-json/wp/v2/';
public static function getPost(int $id )
{
$url = self::$url . 'posts/' . $id;
return self::getJson( $url );
}
public static function getPosts( int $page )
{
$url = self::$url . '/posts?per_page=' . $page;
return collect( self::getJson( $url ) );
}
protected static function getJson( $url)
{
$cached = Cache::get( md5( $url ) );
if( empty( $cached ) ){
$response = file_get_contents($url, false);
$json = json_decode( $response );
//store for 12 hours (12*60 minutes)
Cache::put( md5( $url ), $json, 720 );
return $json;
}else{
return $cached;
}
}
}
<?php
namespace App\Http\Controllers;
class Posts extends Controller {
public function post( $id )
{
$post = Posts::find( $id );
return view( 'wp.post', [
'post' => $post
]);
}
public function posts()
{
$posts = Posts::paginate(15);
return view( 'wp.posts', [
'posts' => $posts
]);
}
}
namespace App\Http\Controllers;
use App\WpApi;
class Posts extends Controller {
public function post( $id )
{
$post = WpApi::getPost( $id );
return view( 'wp.post', [
'post' => $post
]);
}
public function posts( $page )
{
$posts = WpApi::getPosts( $page );
return view( 'wp.posts', [
'posts' => $posts
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment