Building a Hacker News Reader with Lumen
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.
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:
-
Install Lumen: Use Composer:
composer create-project laravel/lumen hnreader --prefer-dist
- 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>
-
Create Database:
mysql -u homestead -psecret CREATE DATABASE hnreader;
-
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:
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'); }); }
Run the migration: php artisan migrate
Routing:
Define routes in app/routes.php
:
$app->get('/{type?}', 'HomeController@index'); // {type?} allows optional parameter
News Updater (app/Console/Commands/UpdateNewsItems.php):
This command fetches and updates news items from the Hacker News API.
<?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) ... } }
Register the command in app/Console/Kernel.php
:
protected $commands = [ 'App\Console\Commands\UpdateNewsItems', ]; protected function schedule(Schedule $schedule) { $schedule->command('update:news_items')->dailyAt('19:57'); }
Add a cron job (replace /path/to/hn-reader
with your actual path):
* * * * * php /path/to/hn-reader/artisan schedule:run >> /dev/null 2>&1
News Page Controller (app/Http/Controllers/HomeController.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')); } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.
