>该教程通过使用黑客新闻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中文网其他相关文章!