IronMQ和Laravel:实施

Welcome back to the IronMQ and Laravel series – this is the second and final part in which we finalize our background-job enabled web app.

欢迎回到IronMQ和Laravel系列–这是我们最后一个启用后台工作的Web应用程序的第二部分也是最后一部分。

There are several tutorials out there related to queues already – for example: https://vimeo.com/64703617 where Taylor teaches you how to write to a file using queues. In this tutorial, we will try something different.

那里已经有几本与队列相关的教程-例如: https : //vimeo.com/64703617 ,其中Taylor教您如何使用队列写入文件。 在本教程中,我们将尝试不同的方法。

We will make a jobs table which has job_id, and the status of the job. When you put a job on the queue, the job status will be queued and when we receive the job, we set the status to running. Accordingly, after finishing it we will mark it finished.

我们将其中有一个工作job_id和作业的状态。 当您将作业放在队列中时,作业状态将排队,而当我们收到作业时,我们将状态设置为running 。 因此,完成后我们将其标记为完成

Later, we will resize images.

稍后,我们将调整图像大小。

工作表 (Jobs Table)
第1步 (Step 1)

Let’s create a jobs table:

让我们创建一个作业表:

php artisan migrate:make create_jobs_table

Go to app/database/migrations/xxxxx_create_jobs_table.php and add the following (This code is extracted from app/database/migrations/xxxxx_create_jobs_table.php, so edit your file accordingly):

转到app/database/migrations/xxxxx_create_jobs_table.php并添加以下内容(此代码是从app/database/migrations/xxxxx_create_jobs_table.php ,因此请相应地编辑文件):

public function up()
{
    Schema::create('jobs', function($table)
{
    $table->increments('id');
    $table->string('job_id');
    $table->enum('status', array('queued', 'running','finished'))->default('queued');
    $table->timestamps();
    });
}

public function down()
{
    Schema::drop('jobs');
}

Here we created a table with the columns job_id, status and timestamps. Run php artisan migrate to create the table.

在这里,我们创建了一个包含job_idstatustimestamps列的表。 运行php artisan migrate创建表。

第2步 (Step 2)

Create a file job.php in app/models with the following content:

app/models创建具有以下内容的文件job.php

<?php

class Job extends Eloquent {

    protected $table = 'jobs';

    protected $fillable = array('job_id', 'status');

}

Make a JobController using the following command:

使用以下命令制作JobController:

php artisan controller:make JobController

and add the following in the app/routes.php file:

并在app/routes.php文件中添加以下内容:

Route::resource('job','JobController');

Go to JobController populate the index method.

转到JobController填充索引方法。

public function index()
{
    $jobs = Job::all();

    return View::make('job.index')->with('jobs',$jobs);
}

Before we go ahead we need to set up our views. First, let’s create a views/master.blade.php which will serve as a template.

在继续之前,我们需要树立我们的观点。 首先,让我们创建一个views/master.blade.php作为模板。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel PHP Framework</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-12 well">
                Let's Learn Queues
            </div>

            @yield('content')
        </div>
    </div>

</body>
</html>

Let’s make a view for our jobs. Put the following content in app/views/job/index.blade.php

让我们来看看我们的工作。 将以下内容放入app/views/job/index.blade.php

@extends('master')

@section('content')
<div class="col-md-12">
    <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Job ID</th>
                <th>Status</th>
            </tr>
        </thead>

        <tbody>
            @foreach($jobs as $job)
                <tr>
                    <td>{{ $job->id }}</td>
                <td>{{ $job->job_id }}</td>
                <td>{{ $job->status }}</td>
                </tr>
            @endforeach
        </tbody>

    </table>
</div>
@stop

As we have no jobs now, we won’t see anything if we go to http://localhost:8000/job.

由于我们现在没有工作,因此如果访问http://localhost:8000/job ,将看不到任何内容。

Now let’s create a new job (where we write a string to a file) and then update the status of the job to ‘finished’.

现在,让我们创建一个新作业(在其中将字符串写入文件),然后将作业状态更新为“完成”。

public function create()
{
    $job_id = Queue::push('JobController@run',array('string' => 'Hello World '));

    Job::create(array('job_id' => $job_id));

    return Redirect::route('job.index');
}

Note that above we pushed a method ‘run’ onto the queue with some data. So we need to create a method ‘run’ in JobController.

请注意,上面我们将带有一些数据的方法“运行”推入队列。 因此,我们需要在JobController中创建一个“运行”方法。

public function run($job,$data)
{

    $job_id = $job->getJobId(); // Get job id

    $ejob = Job::where('job_id',$job_id)->first(); // Find the job in database

    $ejob->status = 'running'; //Set job status to running

    $ejob->save();

    File::append('public/queue.txt',$data['string'].$job_id.PHP_EOL); //Add content to file

    $ejob->status = 'finished'; //Set job status to finished

    $ejob->save();

    return true;
}

At this point you can test this. Let’s give it a go with the url generated by ngrok. Please note that your url will be different from mine.

此时,您可以对此进行测试。 让我们来看看ngrok生成的url。 请注意,您的网址将与我的网址不同。

  1. Go to http://953ffbb.ngrok.com (It should be working)

    转到http://953ffbb.ngrok.com (应该可以运行)

  2. In Iron MQ Dashboard -> Project -> Queues -> Your Queue -> Push Queues : You should see http://953ffbb.ngrok.com/queue/receive under subscribers.

    在Iron MQ仪表板->项目->队列->您的队列->推送队列中:在订阅者下,您应该看到http://953ffbb.ngrok.com/queue/receive

  3. Go to http://953ffbb.ngrok.com/job : It should show a list of jobs (It’s possible there are no jobs as we didn’t create any).

    转到http://953ffbb.ngrok.com/job :它应该显示作业列表(由于我们未创建任何作业,因此可能没有作业)。

  4. Create a job: http://953ffbb.ngrok.com/job/create. This will create a job and come back to http://953ffbb.ngrok.com/job where you see your job with job_id and status “queued”.

    创建工作:http: //953ffbb.ngrok.com/job/create 。 这将创建一个作业,并返回到http://953ffbb.ngrok.com/job ,在该作业中您看到具有job_id和“已排队​​”状态的作业。

  5. Refresh the page: http://953ffbb.ngrok.com/job and you can see that the status is changed to ‘finished’ and find the file public/queue.txt with some text.

    刷新页面:http: //953ffbb.ngrok.com/job ,您可以看到状态更改为“完成”,并找到带有一些文本的文件public/queue.txt

That’s it! We pushed a job into the queue, Iron sent the job to the subscriber and we completed our job (wrote data to file and changed the status).

而已! 我们将作业推入队列,Iron将作业发送给订户,然后完成了我们的工作(将数据写入文件并更改了状态)。



调整照片大小 (Resize Photos)

Let’s upload photos and resize them using Intervention.

让我们上传照片并使用Intervention调整大小。

Make a PhotoController to handle operations on photos:

创建一个PhotoController来处理照片上的操作:

php artisan controller:make PhotoController

Add a route for photos in app/routes.php

app / routes.php中为照片添加路线

Route::resource('photo','PhotoController');

Let’s make a table for photos:

让我们为照片制作一张桌子:

php artisan migrate:make create_photos_table

Open the file app/database/migrations/xxxxxx_create_photos_table.php and the following content:

打开文件app/database/migrations/xxxxxx_create_photos_table.php和以下内容:

public function up()
{
    Schema::create('photos', function($table)
{
    $table->increments('id');

        $table->string('path');

        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('photos');
}

And then run php artisan migrate to create the table.

然后运行php artisan migrate创建表。

Let’s create a model for Photos at app/models/photo.php

让我们在app/models/photo.php为照片创建一个模型

<?php

class Photo extends Eloquent {

    protected $table = 'photos';

    protected $fillable = array('path');

}

Add the index method in PhotoController

在PhotoController中添加index方法

public function index()
{
    $photos = Photo::all();

    return View::make('photo.index')->with('photos',$photos);
}

Add the view for photos index in app/views/photo/index.blade.php

app/views/photo/index.blade.php添加照片视图索引

@extends('master')

@section('content')
<div class="col-md-12">
    <h2>Photos</h2>
    <a href="{{ route('photo.create') }}" class="btn btn-primary">Upload New Photo</a> <br><br>
    <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Path</th>
            </tr>
        </thead>

        <tbody>
            @foreach($photos as $photo)
                <tr>
                    <td>{{ $photo->id }}</td>
                <td>{{ $photo->path }}</td>

                    <td>
                        <a href="{{ route('photo.edit', $photo->id) }}" class="btn btn-primary btn-xs"> Resize </a>
                    </td>
                </tr>
            @endforeach
        </tbody>

    </table>
</div>
@stop

You can now visit: http://localhost:8000/photo and check the page (but there won’t be any photos)

您现在可以访问: http:// localhost:8000 / photo并检查页面(但不会有任何照片)

We need a page to upload photos, so let’s make a view and hook in a few methods to achieve that.

我们需要一个页面来上传照片,因此让我们进行查看并添加一些实现该目标的方法。

Put this content in app/views/photo/create.blade.php

将此内容放在app/views/photo/create.blade.php

@extends('master')

@section('content')
<div class="col-md-12">
    <h2>Upload New Photo</h2>

    {{ Form::open(array('route' => array('photo.store'),'files' => true)) }}

    <div class="form-group">
        {{ Form::file('photo') }}
    </div>

    {{ Form::submit('Upload',array('class' => 'btn btn-blue btn-primary')) }}

    {{ Form::close() }}

</div>
@stop

Make changes in app/controllers/PhotoController.php

app/controllers/PhotoController.php

public function create()
{
    return View::make('photo.create');
}

public function store()
{
    $file = Input::file('photo'); // Get the file

    $extension = $file->getClientOriginalExtension(); //Get the extension

    $filename = time().'.'.$extension; //Prepare filename

    $upload_success = $file->move('public/uploads', $filename); //Move file

    Photo::create(array('path' => 'uploads/'.$filename )); //Store info in DB

    return Redirect::route('photo.index');
}

Go to http://localhost:8000/photo and click on ‘Upload New Photo’ and upload the photo. You can go public/uploads and find your photo. At the same time you can find the photos list along with a resize button. Now, we need a form where we can mention width and height to resize.

转到http://localhost:8000/photo ,然后单击“上传新照片”并上传照片。 您可以public/uploads并找到您的照片。 同时,您可以找到照片列表以及调整大小按钮。 现在,我们需要一种可以提及宽度和高度以调整大小的表格。

Put this content in app/views/photo/edit.blade.php

将此内容放在app/views/photo/edit.blade.php

@extends('master')

@section('content')
<div class="col-md-12">
    <h2>Resize Photo</h2>

    {{ Form::open(array('route' => array('photo.update',$photo->id), 'method' => 'PUT')) }}

    <div class="form-group">
        {{ Form::label('width', 'Width') }}

        {{ Form::text('width') }}
    </div>

    <div class="form-group">
        {{ Form::label('height', 'Height') }}

        {{ Form::text('height') }}
    </div>

    {{ Form::submit('Submit',array('class' => 'btn btn-blue btn-primary')) }}

    {{ Form::close() }}

</div>
@stop

The following three methods will be doing our work to resize images:

以下三种方法将用于调整图像大小:

public function edit($id)
    {
        $photo = Photo::find($id);

        return View::make('photo.edit')->with('photo', $photo);
    }

    public function update($id)
    {
        $data['photo_id'] = $id;
        $data['width'] = Input::get('width');
        $data['height'] = Input::get('height');

        $job_id = Queue::push('PhotoController@resize', $data); //Put a job in queue to resize

        Job::create(array('job_id' => $job_id));

        return Redirect::route('photo.index');
    }

    public function resize($job, $data)
    {

        $job_id = $job->getJobId(); // Get job id

        $ejob = Job::where('job_id', $job_id)->first(); // Find the job in database

        $ejob->status = 'running'; //Set job status to running

        $ejob->save();

        $photo = Photo::find($data['photo_id']);

        $filename = $data['width'] . '_' . $data['height'] . '_' . basename($photo->path);

        Image::open('public/' . $photo->path)
            ->resize($data['width'], $data['height'], true)
            ->save('public/uploads/' . $filename);

        Photo::create(array('path' => 'uploads/' . $filename));

        $ejob->status = 'finished'; //Set job status to finished

        $ejob->save();

        return true;
    }

Now if you click on resize and submit the form, a job will be queued. If you refresh the photos page, you will find the new photo.

现在,如果您单击调整大小并提交表单,则作业将排队。 如果刷新照片页面,则会找到新照片。

结论 (Conclusion)

In this article series we implemented IronMQ with Laravel to add background image processing capabilities to our web app. See how simple it was? Did you have any problems? Want to see more? Let us know!

在本系列文章中,我们使用Laravel实现了IronMQ,以将背景图像处理功能添加到我们的Web应用程序中。 看看有多简单? 你有什么问题吗? 想看更多? 让我们知道!

翻译自: https://www.sitepoint.com/ironmq-laravel-implementation/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值