如何使用Laravel实时处理推文

This tutorial will show how to use the Twitter Streaming APIs to process tweets in real-time from a Laravel application. There are a variety of use cases for this: perhaps you want to auto-respond to mentions of your company, run a contest via Twitter, or create support tickets when users complain about your product. For this tutorial, we'll build a "featured tweets" widget to display approved tweets on our app's home page.

本教程将展示如何使用Twitter Streaming API从Laravel应用程序实时处理推文。 这样做有多种用例:也许您想自动回复提及您公司的信息,通过Twitter进行竞赛,或者在用户抱怨您的产品时创建支持通知单。 对于本教程,我们将构建一个“功能性推文”小部件,以在应用程序的主页上显示批准的推文。

You might first look at the Twitter REST APIs, which many developers are familiar with. These APIs allow you to do a lot of cool things: read and write tweets on behalf of app users, manage followers and lists, and more. However, if you want to process tweets as they are sent, the REST APIs are very difficult to manage. Pagination and rate limiting become a logistical nightmare quickly.

您可能首先看一下许多开发人员都熟悉的Twitter REST API。 这些API使您可以做很多很酷的事情:代表应用程序用户读写推文,管理关注者和列表等。 但是,如果要在发送推文时对其进行处理,则REST API很难管理。 分页和限制速率很快成为后勤上的噩梦。

Whereas the REST APIs force you to request information, the Streaming APIs feed information to you. You can read more about how it works in the documentation, but it's basically a pipe from Twitter to your application which delivers a continual flow of tweets.

REST API会强制您请求信息,而Streaming API会向您提供信息。 您可以在文档中阅读有关它的工作原理的更多信息,但从本质上讲,它是从Twitter到您的应用程序的管道,它提供了连续的tweet流。

By the end of the tutorial, you'll have a constantly updating collection of tweets in your app that you can approve or disapprove to show up in your home page. Here's a preview of what you'll end up with.

在本教程结束时,您将在您的应用程序中拥有不断更新的tweet集合,您可以批准或不批准它们显示在主页上。 这是最终的预览。

总览 ( Overview )

工具 (The Tools)

  • Public Streaming API: There are three Streaming APIs, but the one we care about is the Public API - and more specifically, the 'filter' endpoint. This endpoint will deliver a stream of all public tweets, filtered by the keywords that you define.

    公用流API:共有三种流API,但我们关注的是公用API,更具体地说,是“过滤器”端点。 该端点将提供所有公共推文的流,并按您定义的关键字过滤。
  • Phirehose: The Phirehose library takes care of authentication and other implementation details for the Streaming API.

    Phirehose: Phirehose库负责Streaming API的身份验证和其他实现细节。
  • Homestead: Although you can build your app with your environment of choice, this tutorial will assume you are using Homestead.

    Homestead:尽管您可以使用自己选择的环境构建应用程序,但是本教程将假定您正在使用Homestead

笔记 (Notes)

  • The Streaming APIs are treated specially by Twitter. You can only have one connection open from a single Twitter app.

    Twitter特别对待Streaming API。 您只能从一个Twitter应用程序打开一个连接。
  • Because of the special nature of the connection to the Streaming API, it's important that it is separate from the web-facing part of your app. In this tutorial, we'll be creating the connection with an Artisan console command.

    由于与Streaming API的连接具有特殊的性质,因此与应用程序的面向Web的部分分开是很重要的。 在本教程中,我们将使用Artisan控制台命令创建连接。
  • Because the Streaming APIs are so finnicky, it's important not to do anything intensive with the tweets in the same process that is collecting them. In this tutorial you'll simply be placing the tweets onto a queue.

    由于Streaming API如此严格,因此重要的是, 不要在收集推文的同一过程中对推文进行任何密集的工作。 在本教程中,您将只是将这些推文放入一个队列中。
  • Be careful with the terms you are tracking. If you try to track all mentions of Taylor Swift, your app will probably melt.

    请注意所跟踪的术语。 如果您尝试跟踪对Taylor Swift的所有提及,则您的应用程序可能会崩溃。

应用程式结构 (App Structure)

Here are the major pieces of the app that we'll be creating:

以下是我们将创建的应用程序的主要部分:

  • A class called TwitterStream which will extend Phirehose and place tweets onto the queue as they arrive

    一个名为TwitterStream的类,它将扩展Phirehose并将推文在到达时放入队列中
  • An Artisan command, ConnectToStreamingAPI, which will open a connection to the Streaming API with an instance of TwitterStream

    一个Artisan命令ConnectToStreamingAPI ,它将使用TwitterStream实例打开与Streaming API的连接。
  • A job class, ProcessTweet, which will contain the handler to process tweets when they are pulled off the queue

    作业类 ProcessTweet ,将包含处理程序,用于在将其从队列中拉出时对其进行处理。
  • A Tweet Eloquent model

    Tweet口才模型
  • A few blade templates to display the tweet widget

    一些刀片模板显示推文小部件

While reading through the tutorial, you can follow along with this Github repo. It has separate commits for each step: https://github.com/dabernathy89/Laravel-Twitter-Streaming-API-Demo

阅读本教程时,您可以遵循此Github存储库。 每个步骤都有单独的提交: https : //github.com/dabernathy89/Laravel-Twitter-Streaming-API-Demo

步骤1:建立新的Laravel应用程式 ( Step 1: Create a New Laravel App )

Using the Laravel installer, create a new Laravel instance:

使用Laravel 安装程序 ,创建一个新的Laravel实例:

laravel new twitter-stream-test

laravel new twitter-stream-test

Once that's done, add the app to your Homestead configuration file. Don't forget to edit your hosts file with whatever custom domain you added to the configuration. Boot up Homestead:

完成后,将应用程序添加到Homestead配置文件中 。 不要忘记使用添加到配置中的任何自定义域来编辑hosts文件。 启动Homestead:

homestead up --provision

homestead up --provision

SSH into Homestead:

SSH进入Homestead:

homestead ssh

homestead ssh

Finally, cd into your app's folder.

最后, cd到您的应用程序的文件夹中。

步骤2:安装Phirehose ( Step 2: Install Phirehose )

Next, you need to pull in the Phirehose library. Run composer require fennb/phirehose to grab the latest version. Phirehose doesn't support PSR-0 or PSR-4 autoloading, so you'll need to use Composer's classmap autoloading option. Add a line just after the database entry:

接下来,您需要引入Phirehose库。 运行composer require fennb/phirehose来获取最新版本。 Phirehose不支持PSR-0或PSR-4自动加载,因此您需要使用Composer的classmap自动加载选项。 在database条目之后添加一行:

"classmap": [
            "database",
            "vendor/fennb/phirehose/lib"
        ],

步骤3:创建ProcessTweet作业 ( Step 3: Create the ProcessTweet Job )

I mentioned in the overview that we will be putting all of the tweets from the Streaming API onto a queue. In Laravel 5.2, there are special Job classes that are meant for processing items in a queue. Your app will have a job called ProcessTweet which will be responsible for pulling tweets off the queue and doing something with them. You can create the job with a simple Artisan command:

我在概述中提到,我们将把来自Streaming API的所有推文放入队列中。 在Laravel 5.2中,有一些特殊的Job类用于处理队列中的项目。 您的应用程序将有一个名为ProcessTweet的工作,它将负责将tweet从队列中拉出并对其进行处理。 您可以使用简单的Artisan命令创建作业:

php artisan make:job ProcessTweet

php artisan make:job ProcessTweet

This will generate a Job class in your app/Jobs folder. You only need to make two adjustments to it for now.

这将在您的app/Jobs文件夹中生成一个Job类。 您现在只需要对其进行两次调整。

  1. You know that this class will be processing a tweet (even though we haven't set that up yet). Pass a $tweet variable into the constructor and set it as a property.

    您知道该类将处理一条推文(即使我们尚未设置)。 将$ tweet变量传递到构造函数中并将其设置为属性。
  2. Do something with the tweet in the handle() method. For now you can just var_dump() some basic information from the tweet.

    使用handle()方法中的tweet进行操作。 现在,您只需var_dump()从推文中获取一些基本信息。
<?php

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class ProcessTweet extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $tweet;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($tweet)
    {
        $this->tweet = $tweet;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $tweet = json_decode($this->tweet,true);
        var_dump($tweet['text']) . PHP_EOL;
        var_dump($tweet['id_str']) . PHP_EOL;
    }
}

步骤4:创建TwitterStream类 ( Step 4: Create The TwitterStream Class )

To use Phirehose, you need to create a simple class that extends the base Phirehose class. This can go wherever you like, but I've just placed it directly in the app folder. Here's the full class:

要使用Phirehose,您需要创建一个简单的类来扩展Phirehose基类。 这可以随心所欲,但我只是将其直接放置在app文件夹中。 这是完整的课程:

<?php

namespace App;

use OauthPhirehose;
use App\Jobs\ProcessTweet;
use Illuminate\Foundation\Bus\DispatchesJobs;

class TwitterStream extends OauthPhirehose
{
    use DispatchesJobs;

    /**
    * Enqueue each status
    *
    * @param string $status
    */
    public function enqueueStatus($status)
    {
        $this->dispatch(new ProcessTweet($status));
    }
}

A couple of things to note:

需要注意的几件事:

  • The class pulls in the DispatchesJobs trait to make it easy to push the tweet onto the queue.

    该类引入DispatchesJobs特征以使其很容易将推文推入队列。
  • There is only a single method, enqueueStatus, which will be called by Phirehose for each tweet.

    只有一个方法enqueueStatus ,对于每个推文, enqueueStatus都会调用该方法。

步骤5:注册TwitterStream类 ( Step 5: Register the TwitterStream Class )

You need to register the TwitterStream class with the Laravel container so that it can pull in its dependencies properly. In the register method of your AppServiceProvider class, add the following:

您需要向Laravel容器注册TwitterStream类,以便它可以正确获取其依赖项。 在您的AppServiceProvider类的register方法中,添加以下内容:

$this->app->bind('App\TwitterStream', function ($app) {
            $twitter_access_token = env('TWITTER_ACCESS_TOKEN', null);
            $twitter_access_token_secret = env('TWITTER_ACCESS_TOKEN_SECRET', null);
            return new TwitterStream($twitter_access_token, $twitter_access_token_secret, Phirehose::METHOD_FILTER);
        });

You will also need to add use Phirehose; and use App\TwitterStream; at the top of your service provider. Don't worry about the environment variables for now - you'll create them shortly.

您还需要添加use Phirehose;use App\TwitterStream; 在您的服务提供商的顶部。 现在不用担心环境变量-您将很快创建它们。

步骤6:创建Artisan命令 ( Step 6: Create the Artisan Command )

Generate an Artisan command so that you can initiate the Streaming API connection over the command line:

生成Artisan命令,以便您可以通过命令行启动Streaming API连接:

php artisan make:console ConnectToStreamingAPI

php artisan make:console ConnectToStreamingAPI

This will generate the boilerplate console command class. Then you need to:

这将生成样板控制台命令类。 然后,您需要:

  • Update the command's signature and description

    更新命令的签名和描述
  • Pull in an instance of the TwitterStream class through the constructor

    通过构造函数TwitterStream类的实例
  • In the command's handle() method, finish configuring the Phirehose object, including your search terms, and open the connection

    在命令的handle()方法中,完成配置Phirehose对象(包括您的搜索词),然后打开连接

Here's what the completed command looks like. It will pull in tweets that contain the keyword scotch_io:

这是完成的命令的样子。 它将拉入包含关键字scotch_io推文:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\TwitterStream;

class ConnectToStreamingAPI extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'connect_to_streaming_api';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Connect to the Twitter Streaming API';

    protected $twitterStream;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(TwitterStream $twitterStream)
    {
        $this->twitterStream = $twitterStream;

        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $twitter_consumer_key = env('TWITTER_CONSUMER_KEY', '');
        $twitter_consumer_secret = env('TWITTER_CONSUMER_SECRET', '');

        $this->twitterStream->consumerKey = $twitter_consumer_key;
        $this->twitterStream->consumerSecret = $twitter_consumer_secret;
        $this->twitterStream->setTrack(array('scotch_io'));
        $this->twitterStream->consume();
    }
}

You also need to register the command. Simply update the $commands property in the App\Console\Kernel class:

您还需要注册命令 。 只需更新App\Console\Kernel类中的$commands属性:

protected $commands = [
        Commands\ConnectToStreamingAPI::class
    ];

步骤7:建立Twitter应用程式 ( Step 7: Create a Twitter App )

Generate an app with Twitter, and grab the keys and access tokens. Add them to your .env file:

使用Twitter 生成一个应用程序 ,并获取密钥和访问令牌。 将它们添加到您的.env文件中:

TWITTER_CONSUMER_KEY=123
TWITTER_CONSUMER_SECRET=123
TWITTER_ACCESS_TOKEN=123
TWITTER_ACCESS_TOKEN_SECRET=123

TWITTER_CONSUMER_KEY=123
TWITTER_CONSUMER_SECRET=123
TWITTER_ACCESS_TOKEN=123
TWITTER_ACCESS_TOKEN_SECRET=123

步骤8:配置队列驱动程序 ( Step 8: Configure Your Queue Driver )

You can set up the queue however you want, but for demonstration purposes, the database driver will work fine. To set that up, update your .env file:

您可以根据需要设置队列,但是出于演示目的,数据库驱动程序可以正常工作。 要进行设置,请更新您的.env文件:

QUEUE_DRIVER=database

QUEUE_DRIVER=database

By default, your app will look for a database with the name homestead. Don't forget to update this in your .env file if you want a separate database for your app:

默认情况下,您的应用程序将查找名称为homestead的数据库。 如果要为应用程序使用单独的数据库,请不要忘记在.env文件中进行更新:

DB_DATABASE=twitterstreamtest

DB_DATABASE=twitterstreamtest

You'll also need to run the following commands to prepare the database queue:

您还需要运行以下命令来准备数据库队列:

php artisan queue:table

php artisan queue:table

php artisan migrate

php artisan migrate

第9步:阅读一些推文! ( Step 9: Read some tweets! )

Now you should be ready to start processing some tweets. Run your Artisan commmand:

现在,您应该准备开始处理一些推文了。 运行您的Artisan命令:

php artisan connect_to_streaming_api

php artisan connect_to_streaming_api

You'll see some information about the connection in your console from Phirehose. It won't tell you every time a tweet is processed, but it will give you an update every once in a while on the status of the connection.

您将在Phirehose的控制台中看到有关连接的一些信息。 它不会在每次处理Tweet时告诉您,但会不定期地为您提供连接状态的更新。

Before too long, you should have some tweets about Scotch.io sitting in a queue. To check if tweets are coming in, head over to your database and look in the jobs table:

不久之后,您应该将有关Scotch.io的一些推文排在队列中。 要检查是否有鸣叫,请转到您的数据库并查看jobs表:

Now let's try processing the queue. Open up a new shell window, navigate to your app in Homestead, and pull the first item off the queue:

现在,让我们尝试处理队列。 打开一个新的Shell窗口,导航到Homestead中的应用程序,然后将第一个项目从队列中拉出:

php artisan queue:work

php artisan queue:work

If you don't have anything in the queue yet, you can add your own by sending this tweet (be sure to open it in a new tab).

如果队列中还没有任何内容,则可以通过发送此鸣叫来添加自己的消息 (请确保在新选项卡中将其打开)。

If everything went right, you should see the text and id of the tweet in the console, from the handle() method in the ProcessTweet job.

如果一切正常,您应该在控制台中从ProcessTweet作业的handle()方法中看到该推文的文本和ID。

步骤10:设置推文模型 ( Step 10: Set Up the Tweet Model )

Now that you have successfully connected to the Streaming API, it's time to start building your featured tweets widget. Start by generating a Tweet model and a corresponding database migration:

现在您已成功连接到Streaming API,是时候开始构建您的特色推文窗口小部件了。 首先生成Tweet模型和相应的数据库迁移:

php artisan make:model Tweet --migration

php artisan make:model Tweet --migration

We're going to add some properties to our model, so go ahead and set those now. Below is what your completed model and migration should look like - note that I'm using a string for the model ID, because Twitter IDs are massive.

我们将在模型中添加一些属性,所以现在就进行设置。 以下是您完成的模型和迁移的外观-请注意,我使用字符串作为模型ID,因为Twitter ID很大。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tweet extends Model
{
    protected $fillable = ['id','json','tweet_text','user_id','user_screen_name','user_avatar_url','public','approved'];
}
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTweetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tweets', function (Blueprint $table) {
            $table->string('id');
            $table->text('json');
            $table->string('tweet_text')->nullable();
            $table->string('user_id')->nullable();
            $table->string('user_screen_name')->nullable();
            $table->string('user_avatar_url')->nullable();
            $table->boolean('approved');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tweets');
    }
}

Finally, migrate your database:

最后,迁移数据库:

php artisan migrate

php artisan migrate

步骤11:使ProcessTweet作业有用 ( Step 11: Make the ProcessTweet Job Useful )

Right now the ProcessTweet job is just displaying some information about the tweet in the console. Update the handle method so that it saves the tweets to the database:

现在, ProcessTweet作业仅在控制台中显示有关该tweet的一些信息。 更新handle方法,以便将推文保存到数据库中:

public function handle()
    {
        $tweet = json_decode($this->tweet,true);
        $tweet_text = isset($tweet['text']) ? $tweet['text'] : null;
        $user_id = isset($tweet['user']['id_str']) ? $tweet['user']['id_str'] : null;
        $user_screen_name = isset($tweet['user']['screen_name']) ? $tweet['user']['screen_name'] : null;
        $user_avatar_url = isset($tweet['user']['profile_image_url_https']) ? $tweet['user']['profile_image_url_https'] : null;

        if (isset($tweet['id'])) {
            Tweet::create([
                'id' => $tweet['id_str'],
                'json' => $this->tweet,
                'tweet_text' => $tweet_text,
                'user_id' => $user_id,
                'user_screen_name' => $user_screen_name,
                'user_avatar_url' => $user_avatar_url,
                'approved' => 0
            ]);
        }
    }

When that's done, you can run the queue listener to empty out the queue and import the tweets into your database:

完成后,您可以运行队列侦听器以清空队列并将推文导入数据库:

php artisan queue:listen

php artisan queue:listen

You should now be able to see some tweets in your database:

现在,您应该能够在数据库中看到一些推文:

步骤12:设置身份验证 ( Step 12: Set Up Authentication )

Thanks to Laravel's auth scaffolding, this is probably the easiest step. Just run:

感谢Laravel的身份验证脚手架,这可能是最简单的步骤。 赶紧跑:

php artisan make:auth

php artisan make:auth

步骤13:将推文传递到“欢迎”视图中 ( Step 13: Pass Tweets Into the Welcome View )

For now your app will only display the featured tweets widget on the main landing page. Authenticated users are going to be allowed to approve or disapprove tweets, so they will receive all tweets (paginated). Visitors will only be able to see the five most recent approved tweets.

目前,您的应用将仅在主登录页面上显示精选的tweets小部件。 经过身份验证的用户将被允许批准或不批准推文,因此他们将收到所有推文(已分页)。 访客只能看到五个最新批准的推文。

Pass the tweets into the existing welcome view by updating the main route in your routes.php file:

通过更新routes.php文件中的主要路由, routes.php文传递到现有的welcome视图中:

Route::get('/', function () {
    if (Auth::check()) {
        $tweets = App\Tweet::orderBy('created_at','desc')->paginate(5);
    } else {
        $tweets = App\Tweet::where('approved',1)->orderBy('created_at','desc')->take(5)->get();
    }

    return view('welcome', ['tweets' => $tweets]);
});

步骤14:创建刀片模板 ( Step 14: Create The Blade Templates )

You'll need to create three blade templates for the featured tweets widget, all stored in the resources/views/tweets directory:

您需要为特色的tweets小部件创建三个刀片模板,所有模板都存储在resources/views/tweets目录中:

  • list.blade.php will be the public-facing list of recent tweets

    list.blade.php将是最近发布的面向公众的推文列表
  • list-admin.blade.php will be the admin-facing list of all tweets

    list-admin.blade.php将是所有推文的面向管理员的列表
  • tweet.blade.php will be a small partial common to both of the tweet lists

    tweet.blade.php将是这两个tweet列表的共同点

The list-admin view is the most complex. The list is wrapped in a form and includes some radio inputs so that registered users can easily approve tweets.

list-admin视图是最复杂的。 该列表以表格的形式包装,并包含一些无线电输入,以便注册用户可以轻松批准推文。

Here are the three templates, in order:

这是按顺序排列的三个模板:

// list.blade.php
@foreach($tweets as $tweet)
    <div class="tweet">
        @include('tweets.tweet')
    </div>
@endforeach
// list-admin.blade.php
<form action="/approve-tweets" method="post">
{{ csrf_field() }}

@foreach($tweets as $tweet)
    <div class="tweet row">
        <div class="col-xs-8">
            @include('tweets.tweet')
        </div>
        <div class="col-xs-4 approval">
            <label class="radio-inline">
                <input
                    type="radio"
                    name="approval-status-{{ $tweet->id }}"
                    value="1"
                    @if($tweet->approved)
                    checked="checked"
                    @endif
                    >
                Approved
            </label>
            <label class="radio-inline">
                <input
                    type="radio"
                    name="approval-status-{{ $tweet->id }}"
                    value="0"
                    @unless($tweet->approved)
                    checked="checked"
                    @endif
                    >
                Unapproved
            </label>
        </div>
    </div>
@endforeach

<div class="row">
    <div class="col-sm-12">
        <input type="submit" class="btn btn-primary" value="Approve Tweets">
    </div>
</div>

</form>

{!! $tweets->links() !!}
// tweet.blade.php
<div class="media">
    <div class="media-left">
        <img class="img-thumbnail media-object" src="{{ $tweet->user_avatar_url }}" alt="Avatar">
    </div>
    <div class="media-body">
        <h4 class="media-heading">{{ '@' . $tweet->user_screen_name }}</h4>
        <p>{{ $tweet->tweet_text }}</p>
        <p><a target="_blank" href="https://twitter.com/{{ $tweet->user_screen_name }}/status/{{ $tweet->id }}">
            View on Twitter
        </a></p>
    </div>
</div>

第15步:在欢迎视图中显示小部件 ( Step 15: Show the Widget in Your Welcome View )

With your blade templates ready, you can now bring them into your welcome view:

准备好刀片模板之后,您现在可以将它们带入welcome视图:

@extends('layouts.app')

@section('content')<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">

            <div class="tweet-list">
                @if(Auth::check())
                    @include('tweets.list-admin')
                @else
                    @include('tweets.list')
                @endif
            </div>

        </div>
    </div>
</div>
@endsection

To get some very basic styling in your list, add the following CSS to your app.blade.php file:

要在列表中获得一些非常基本的样式,请将以下CSS添加到app.blade.php文件中:

.tweet {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 20px;
        }

With that done, you can now view the widget! Head to the browser and visit your app's home page. If you're not seeing any tweets, make sure to run the queue listener (php artisan queue:listen) to process anything that might still be in it. An authorized user should see something like this (with a few more tweets... and less blurry):

完成后,您现在可以查看小部件了! 前往浏览器并访问应用程序的主页。 如果没有看到任何鸣叫,请确保运行队列侦听器( php artisan queue:listen )以处理可能仍在其中的任何内容。 授权用户应看到类似以下内容(带有更多推文...且模糊程度更低):

步骤16:添加批准推文的路线 ( Step 16: Add the Route for Approving Tweets )

The final step is to make the admin list from Step 14 functional. The form in the list-admin template currently points to a nonexistent route. You need to add it to your routes.php file. Inside that route we'll do some basic logic to approve or disapprove tweets. Here's how it should look:

最后一步是使步骤14中的管理员列表正常运行。 list-admin模板中的表单当前指向不存在的路由。 您需要将其添加到routes.php文件。 在该路线内,我们将执行一些基本逻辑来批准或不批准tweet。 外观如下:

Route::post('approve-tweets', ['middleware' => 'auth', function (Illuminate\Http\Request $request) {
    foreach ($request->all() as $input_key => $input_val) {
        if ( strpos($input_key, 'approval-status-') === 0 ) {
            $tweet_id = substr_replace($input_key, '', 0, strlen('approval-status-'));
            $tweet = App\Tweet::where('id',$tweet_id)->first();
            if ($tweet) {
                $tweet->approved = (int)$input_val;
                $tweet->save();
            }
        }
    }
    return redirect()->back();
}]);

With that route in place, you should now be able to mark tweets as approved or disapproved. Try approving some, and then visit the page as an unauthenticated user. It should look something like this:

通过该路由,您现在应该可以将推文标记为已批准或已拒绝。 尝试批准一些,然后以未经身份验证的用户身份访问该页面。 它看起来应该像这样:

结论 ( Conclusion )

That's it! You've connected your Laravel app to the Twitter Streaming API. However, it's not quite production ready. There are a few other things you should consider:

而已! 您已将Laravel应用程序连接到Twitter Streaming API。 但是,它还没有完全准备就绪。 您还应该考虑其他一些事项:

  • You will likely want to configure Supervisor, which Laravel uses to monitor queue listeners, to monitor your Artisan command and restart it if it fails.

    您可能需要配置Supervisor, Laravel用来监视队列侦听器 ,以监视Artisan命令并在失败时重新启动它。
  • You'll want to handle the call to Supervisor into your deployment process.

    您将需要在部署过程中处理对Supervisor的调用。
  • Your search terms might change, and Phirehose provides a method for updating them without interrupting your script.

    您的搜索词可能会更改,Phirehose 提供了一种在不中断脚本的情况下更新它们的方法

Thanks to @mand0z, who's implemented the Phirehose library in Laravel, for answering a couple of questions for me.

感谢@ mand0z ,他在Laravel中实现了Phirehose库,为我回答了几个问题。

翻译自: https://scotch.io/tutorials/how-to-process-tweets-in-real-time-with-laravel

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值