loading...

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... [Read Full]
markdown guide
 

You can just get the current page with

$pageQuery = $_GET['page'];
$currentPage = isset($pageQuery) ? $pageQuery : 1;
 

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';

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]);
});

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]);
    }
}

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 😄.

code of conduct - report abuse