>該教程通過使用黑客新聞API和Lumen Framework構建黑客新聞閱讀器為您引導您。 完成的產品以用戶友好的格式顯示新聞項目。
密鑰功能:
安裝腔:
使用Composer:composer create-project laravel/lumen hnreader --prefer-dist
<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>
mysql -u homestead -psecret CREATE DATABASE hnreader;
和Dotenv::load(__DIR__.'/../');
$app->withFacades();
數據庫設置:創建一個帶有以下架構的遷移():>
運行遷移:php artisan make:migration create_items_table
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'); }); }
路由:php artisan migrate
在中定義路由:>
app/routes.php
>新聞Updater(App/Console/Commands/UpdateNewSitems.php):
$app->get('/{type?}', 'HomeController@index'); // {type?} allows optional parameter
在中註冊命令:
添加一個Cron作業(用您的實際路徑替換
<?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) ... } }
app/Console/Kernel.php
protected $commands = [ 'App\Console\Commands\UpdateNewsItems', ]; protected function schedule(Schedule $schedule) { $schedule->command('update:news_items')->dailyAt('19:57'); }
>
/path/to/hn-reader
* * * * * php /path/to/hn-reader/artisan schedule:run >> /dev/null 2>&1
> 此視圖顯示了被提取的新聞項目。 (CSS和JavaScript包含在原始響應中)。 切記創建
>目錄並添加您的CSS文件。 您還需要調整<?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')); } }
> urlhelper(app/helpers/urlhelper.php):
assets/css
(如原始響應中)UrlHelper
>
可以簡化傳遞到視圖的數據。 整體結構改善了更好的組織。
以上是用管腔建造黑客新聞閱讀器的詳細內容。更多資訊請關注PHP中文網其他相關文章!