我正在使用Laravel 5 的命令总线,但不清楚如何实现验证器类。
我想创建一个 ResizeImageCommandValidator 类,在尝试调整图像大小之前检查图像是否真的是图像。
我想从 ResizeImageCommandHandler resize 方法中提取代码。
if (!($image instanceof Image))
{
throw new ImageInvalidException('ResizeImageCommandHandler');
}
这个想法来自 Laracasts Commands and Domain Events,但 Jeffrey 没有使用 Laravel 5 架构。
这是代码。
ResizeImageCommandHandler.php
<?php namespace App\Handlers\Commands;
use App\Commands\ResizeImageCommand;
use App\Exceptions\ImageInvalidException;
use Illuminate\Queue\InteractsWithQueue;
use Intervention\Image\Image;
class ResizeImageCommandHandler {
/**
* Create the command handler.
*/
public function __construct()
{
}
/**
* Handle the command.
*
* @param ResizeImageCommand $command
* @return void
*/
public function handle($command)
{
$this->resizeImage($command->image, $command->dimension);
}
/**
* Resize the image by width, designed for square image only
* @param Image $image Image to resize
* @param $dimension
* @throws ImageInvalidException
*/
private function resizeImage(&$image, $dimension)
{
if (!($image instanceof Image))
{
throw new ImageInvalidException('ResizeImageCommandHandler');
}
$image->resize($dimension, null, $this->constrainAspectRatio());
}
/**
* @return callable
*/
private function constrainAspectRatio()
{
return function ($constraint) {
$constraint->aspectRatio();
};
}
}
ResizeImageCommand.php
<?php namespace App\Commands;
use App\Commands\Command;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use Image;
class ResizeImageCommand extends Command {
use InteractsWithQueue, SerializesModels;
public $image;
public $savePath;
public $dimension;
/**
* Create a new command instance.
* @param Image $image
* @param string $savePath
* @param int $dimension
* @param int $pose_id
* @param int $state_id
*/
public function __construct(&$image, $savePath, $dimension)
{
$this->image = $image;
$this->savePath = $savePath;
$this->dimension = $dimension;
}
}