laravel 5.4がリリースされたみたいなので気になったところだけ試してみようと思います。
Sanitizing Middleware
5.4で新たにTrim Strings MiddlewareとConvert Empty Strings to NullというMiddlewareが追加されました。
前後の空白除いたり空文字をnullにしてくれます。
- TrimString
protected function transform($key, $value)
{
if (in_array($key, $this->except)) {
return $value;
}
return is_string($value) ? trim($value) : $value;
}
- ConvertEmptyStringsToNull
protected function transform($key, $value)
{
return is_string($value) && $value === '' ? null : $value;
}
Realtime Facades
今までだとサービスコンテナにclassを登録してFacadeを利用していましたが、5.4からclassを直接Facadeとして扱うことができるようになったみたいです。
例)
<?php
namespace App;
class Greeting
{
public function sayHello() {
return 'hello';
}
}
routeやcontrollerから以下のように呼び出せます。
<?php
use Facades\ {
App\Greeting
};
Route::get('/greeting', function() {
return Greeting::sayHello();
});
名前空間は
use Facades\App\Greeting;
とかでもいけます。
Higher Order Messaging for Collections
collectionに対するメソッドが簡潔に記述できるようになりました。
例)
モデルにメソッドを記述
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $table = 'Task';
protected $fillable = ['complete_flag'];
public function complete() {
$this->update(['complete_flag' => 1]);
}
}
Controllerで実行
<?php
namespace App\Http\Controllers;
use App\Task;
class TaskController extends Controller
{
public function index() {
$tasks = Task::all();
/* 5.3以下の記述方法
$tasks->each(function($task) {
$task->complete();
});
*/
$tasks->each->complete();
return;
}
}
<?php
Route::get('/task', 'TaskController@index');
これで/task
にアクセスしTaskテーブルを確認するとcompleteメソッドが実行されたのが分かるかと思います。
この処理の記述はIlluminate\Support\HigherOrderCollectionProxy
にされています。
<?php
namespace Illuminate\Support;
class HigherOrderCollectionProxy
{
/**
* The collection being operated on.
*
* @var \Illuminate\Support\Collection
*/
protected $collection;
/**
* The method being proxied.
*
* @var string
*/
protected $method;
/**
* Create a new proxy instance.
*
* @param \Illuminate\Support\Collection $collection
* @param string $method
* @return void
*/
public function __construct(Collection $collection, $method)
{
$this->method = $method;
$this->collection = $collection;
}
/**
* Proxy accessing an attribute onto the collection items.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->collection->{$this->method}(function ($value) use ($key) {
return is_array($value) ? $value[$key] : $value->{$key};
});
}
/**
* Proxy a method call onto the collection items.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->collection->{$this->method}(function ($value) use ($method, $parameters) {
return $value->{$method}(...$parameters);
});
}
}
他にもBladeの記法やMailがマークダウンで記述可能になったりと変更があったみたいです。
↓まとめてくださってます。
Laravel 5.4 変更点のメモ
また新しくブラウザテストツールのLaravel Duskなども導入されたみたいなので後で触ってみようと思います。
【参考】
https://laravel-news.com/laravel-5-4
https://laravel.com/docs/5.4/releases