>該教程通過使用黑客新聞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
<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>
路由:php artisan migrate
在中定義路由:>
app/routes.php
>新聞Updater(App/Console/Commands/UpdateNewSitems.php):
<code class="language-php">$app->get('/{type?}', 'HomeController@index'); // {type?} allows optional parameter</code>此命令從黑客新聞API中獲取並更新新聞項目。
在中註冊命令:
添加一個Cron作業(用您的實際路徑替換
<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>):
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>
>
/path/to/hn-reader
<code class="language-bash">* * * * * php /path/to/hn-reader/artisan schedule:run >> /dev/null 2>&1</code>>新聞頁面視圖(資源/瀏覽/home.blade.php):
> 此視圖顯示了被提取的新聞項目。 (CSS和JavaScript包含在原始響應中)。 切記創建
>目錄並添加您的CSS文件。 您還需要調整<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>類以匹配您的項目結構。
> urlhelper(app/helpers/urlhelper.php):
assets/css
(如原始響應中)UrlHelper
>
可以簡化傳遞到視圖的數據。 整體結構改善了更好的組織。
以上是用管腔建造黑客新聞閱讀器的詳細內容。更多資訊請關注PHP中文網其他相關文章!