DEV Community

How to load your posts from dev.to onto your site/app

James Robb on November 10, 2019

While working on my website after some time of non-maintenance, I noticed that I had previously been hand coding the links to blog posts I had made...
Collapse
 
devhammed profile image
Hammed Oyedele • Edited

You can just get the current page with

$pageQuery = $_GET['page'];
$currentPage = isset($pageQuery) ? $pageQuery : 1;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jamesrweb profile image
James Robb • Edited

Hey Hammed, thanks for the comment!

I didn't want to add the use of super globals like $_GET, $_POST, $_SESSION, etc since this class should be framework agnostic. By this, I mean, for example you could do any of the following:

Using PHP:

$devPosts = new DevPostFetcher("your_api_key");
$pageQueryParam = $_GET['page'];
$page = 1;

if(isset($pageQueryParam)) {
  $page = (int) $pageQueryParam;
  $page = $page !== 0 ? $page : 1;
}

$devPosts->setPage($page);
$posts = $devPosts->fetch();
require_once 'path/to/template';
Enter fullscreen mode Exit fullscreen mode

Using the Flight framework:

Flight::route('/posts/@page:[1-9]+', function($page) {
  $devPosts = new DevPostFetcher("your_api_key");
  $devPosts->setPage((int) $page);
  $posts = $devPosts->fetch();
  return Flight::render('posts_page', ['posts' => $posts]);
});
Enter fullscreen mode Exit fullscreen mode

Using the Symfony framework:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class PostsController extends AbstractController
{
    /**
     * @Route("/posts/{page}", name="post_list", requirements={"page"="\d+"})
     */
    public function list(int $page)
    {
         $devPosts = new DevPostFetcher("your_api_key");
         $devPosts->setPage($page);
         $posts = $devPosts->fetch();
         return $this->render('posts/index.twig', ['posts' => $posts]);
    }
}
Enter fullscreen mode Exit fullscreen mode

The idea, in short, was to not bias anyones implementation choice but merely to show a reusable class that we will build on top of in later posts and that anyone can use, anywhere. I hope that clears up things a bit for anyone else reading the post and this comment later too ๐Ÿ˜„.