Laravel tap() 的使用方法

Nick Zhang
Sep 4, 2018 · 4 min read

tap()是laravel 的一個Helper function,在很多場合都可以使用得到,tap()的程式架構如下:

function tap($value, $callback)
{
$callback($value);

return $value;
}

其實說穿了就是,取一個值,把這個值傳到callback,然後在callback裡做了一些事,最後再把這個值回傳。

可以看看以下的例子:

public function generateUseAndReturnThing($input)
{
$thing = $this->thingFromInput($input);

$this->doActionToThing($thing);

return $thing;
}

如果用tap()方式來寫,可以變成:

public function generateUseAndReturnThing($input)
{
return tap($this->thingFromInput($input), function ($thing) {
$this->doActionToThing($thing);
});
}

使用tap()的好處就是不需要定義一些暫存的變數,程式碼看起來也會比較簡潔。

在Laravel中也有很多內建的tap()例子,例如eloquent create:

public function create(array $attributes = [])
{
return tap($this->newModelInstance($attributes), function ($instance) {
$instance->save();
});
}

其實它原本的樣式是像這樣:

public function create(array $attributes = [])
{
$instance = $this->newModelInstance($attribtues);

$instance->save();

return $instance;
}

在Laravel 5.4之後也在tap()加上 Higher Order的功能,例如eloquent update:

user->update([
'name' => $name,
'age' => $age,
]);

return $user;

用tap()寫會變成:

return tap($user, function ($user) {
$user->update([
'name' => $name,
'age' => $age,
]);
});

感覺也沒有比較漂亮,不過在Laravel 5.4之後就可以寫成:

return tap($user)->update([
'name' => $name,
'age' => $age,
]);

Collection 中也可以使用tap():

return collect($peopleArray)
->sortBy('name')
->tap(function ($people) {
// Useful for debugging
var_dump($people);
})
->filter(function ($person) {
return $person->syncable === true;
})
->tap(function ($people) {
// Useful for performing some operation without
// requiring a temporary variable
app('thirdPartyService')->syncPeople($people);
});

Nick Zhang

Written by

programmer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade