Project-Flyer-15-Refactoring-Makes-Perfect

跟随 Jeffrey Way 的视频学习,脑子不好,一些细节容易忘记,这里记录下来。相关视频在 laracasts.com
课程名称:Build “ProjectFlyer” With Me(15)

先修改下页面样式,让添加图片到图片的下方,打开 show.blade.php,把:

<form 	id="addPhotosForm" .....>...</form>

表单剪切到

@endforeach

的下面:

<hr>
<form id="addPhotosForm"
action="{{ route('store_photo_path', [$flyer->zip, $flyer->street]) }}"
method="POST"
class="dropzone"
>
{{ csrf_field() }}
</form>

然后给这段 form 添加 if 判断:

@if($user && $user->owns($flyer))
<hr>
<form id="addPhotosForm"
action="{{ route('store_photo_path', [$flyer->zip, $flyer->street]) }}"
method="POST"
class="dropzone"
>
{{ csrf_field() }}
</form>
@endif

刷新可以看到 owns() 方法错误,我们去 User.php 模型里去建立这个方法:

public function owns($relation)
{
return $relation->user_id == $this->id;
}

现在应该可以了,现在打开 FlyerController 控制器,修改 addPhoto 方法:
将:

$photo = $this->makePhoto($request->file('photo'));

修改为:

$photo = Photo::fromFile($request->file('photo'));

注释掉 makePhoto 方法,打开 Photo 模型,添加方法;

public static function fromFile(UploadedFile $file)
{
$photo = new static;
$photo->file = $file;
}

并添加变量$file

protected $file;

删除变量$baseDir,删除 saveAs() 方法,添加下面的方法:

public static function fromFile(UploadedFile $file)
{
$photo = new static;
$photo->file = $file;
return $photo->fill([
'name' => $photo->fileName(),
'path' => $photo->filePath(),
'thumbnail_path' => $photo->thumbnailPath()
]);
}

public function fileName()
{
$name = sha1(
time() . $this->file->getClientOriginalName()
);

$extension = $this->file->getClientOriginalExtension();

return "{$name}.{$extension}";
}

public function filePath()
{
return $this->baseDir() . '/' . $this->fileName();
}

public function thumbnailPath()
{
return $this->baseDir() . '/tn-' . $this->fileName();
}

public function baseDir()
{
return 'uploads/photos';
}

删除 Photo 模型里的 named() 方法,修改move方法名为upload,并修改其内容为:

/**
* Move the photo to the proper folder.
* @return self
*/
public function upload()
{
$this->file->move($this->baseDir(), $this->fileName());
$this->makeThumbnail();
return $this;
}

修改 makeThumbnail 方法为:

/**
* Create a thumbnail for the photo.
* @return void
*/
public function makeThumbnail()
{
Image::make($this->filePath())
->fit(200)
->save($this->thumbnailPath());
}

添加方法 boot():

protected static function boot(){
static::creating(function($photo){
return $photo->upload();
});
}

刷新,上传图片,成功,继续!
重命名FlyerController 控制器里的 addPhoto 方法里的参数类型 ChangeFlyerRequestAddPhotoRequest,并修改ChangeFlyerRequest.php 为 AddPhotoRequest.php,修改类名ChangeFlyerRequestAddPhotoRequest。修改 FlyerController 控制器的引用:

use App\Http\Requests\ChangeFlyerRequest;

use App\Http\Requests\AddPhotoRequest;

删除顶部的多余引用:

use Symfony\Component\HttpFoundation\File\UploadedFile;
0%