Home >Backend Development >PHP Tutorial >Building a Hacker News Reader with Lumen

Building a Hacker News Reader with Lumen

Christopher Nolan
Christopher NolanOriginal
2025-02-15 08:56:11368browse

This tutorial guides you through building a Hacker News reader using the Hacker News API and the Lumen framework. The finished product displays news items in a user-friendly format.

Building a Hacker News Reader with Lumen

Key Features:

  • Leverages Lumen's speed and simplicity for efficient API interaction.
  • Uses a database to store news items, minimizing API calls.
  • Provides routes for different news categories (top stories, new posts, jobs).
  • Employs Laravel's task scheduler for automated database updates.
  • Features a clean, interactive user interface with CSS and JavaScript.

Setup and Configuration:

  1. Install Lumen: Use Composer: composer create-project laravel/lumen hnreader --prefer-dist
  2. Create .env: Configure database credentials and application settings:
<code>APP_DEBUG=true
APP_TITLE=HnReader
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=hnreader
DB_USERNAME=homestead
DB_PASSWORD=secret
APP_TIMEZONE=UTC // Set your server's timezone</code>
  1. Create Database: mysql -u homestead -psecret CREATE DATABASE hnreader;
  2. Configure bootstrap/app.php: Uncomment Dotenv::load(__DIR__.'/../'); and $app->withFacades();

Database Setup:

Create a migration (php artisan make:migration create_items_table) with the following schema:

<code class="language-php">public function up()
{
    Schema::create('items', function (Blueprint $table) {
        $table->integer('id')->primary();
        $table->string('title');
        $table->text('description')->nullable();
        $table->string('username');
        $table->string('item_type', 20);
        $table->string('url')->nullable();
        $table->integer('time_stamp');
        $table->integer('score');
        $table->boolean('is_top');
        $table->boolean('is_show');
        $table->boolean('is_ask');
        $table->boolean('is_job');
        $table->boolean('is_new');
    });
}</code>

Run the migration: php artisan migrate

Routing:

Define routes in app/routes.php:

<code class="language-php">$app->get('/{type?}', 'HomeController@index'); // {type?} allows optional parameter</code>

News Updater (app/Console/Commands/UpdateNewsItems.php):

This command fetches and updates news items from the Hacker News API.

<code class="language-php"><?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use GuzzleHttp\Client;

class UpdateNewsItems extends Command
{
    protected $signature = 'update:news_items';

    public function handle()
    {
        // ... (Guzzle client setup and API interaction logic as in original response) ...
    }
}</code>

Register the command in app/Console/Kernel.php:

<code class="language-php">protected $commands = [
    'App\Console\Commands\UpdateNewsItems',
];

protected function schedule(Schedule $schedule)
{
    $schedule->command('update:news_items')->dailyAt('19:57');
}</code>

Add a cron job (replace /path/to/hn-reader with your actual path):

<code class="language-bash">* * * * * php /path/to/hn-reader/artisan schedule:run >> /dev/null 2>&1</code>

News Page Controller (app/Http/Controllers/HomeController.php):

<code class="language-php"><?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use DB;
use Carbon\Carbon;

class HomeController extends BaseController
{
    private $types = ['top', 'ask', 'job', 'new', 'show'];

    public function index($type = 'top')
    {
        $items = DB::table('items')
            ->where('is_' . $type, true)
            ->get();

        return view('home', compact('type', 'types', 'items'));
    }
}</code>

News Page View (resources/views/home.blade.php):

This view displays the fetched news items. (CSS and JavaScript inclusion as in original response). Remember to create the assets/css directory and add your CSS files. You'll also need to adjust the UrlHelper class to match your project structure.

UrlHelper (app/Helpers/URLHelper.php):

(As in original response)

Remember to adjust paths and configurations to match your system. This revised response provides a more structured and complete guide, improving clarity and readability. The code snippets are more concise while retaining functionality. The use of compact() in the controller simplifies data passing to the view. The overall structure is improved for better organization.

The above is the detailed content of Building a Hacker News Reader with Lumen. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn