無意間發現 Laravel 在 public/index.php 有這樣一段:
define('LARAVEL_START', microtime(true));
這樣要取得程式執行時間就方便多了,不用做一些 workaround。
若要取得程式執行時間,可以這樣寫:
$elapsed = mocrotime(true) - LARAVEL_START;
軟體開發和生活瑣事
無意間發現 Laravel 在 public/index.php 有這樣一段:
define('LARAVEL_START', microtime(true));
這樣要取得程式執行時間就方便多了,不用做一些 workaround。
若要取得程式執行時間,可以這樣寫:
$elapsed = mocrotime(true) - LARAVEL_START;
在 Laravel Queue 的文件中,要 dispatch job 到 queue 中,語法如下:
MyJob::dispatch($data);
如果有注意的話,這段執行以後,job 並不會馬上進 queue,而是會先得到一個 PendingDispatch 物件。
由網路上的說明 PendingDispatch 物件,會在 response 完成、程式正常結束時,才會觸發並將 job 放進 queue。
若要在 Laravel Tinker 或是 console 中,不等待、直接將 job 放進 queue,則語法須改為下方所示:
$job = new MyJob($data);
app(\Illuminate\Contracts\Bus\Dispatcher::class)
->dispatch($job);
在 Blade template engine 中使用判斷式:
@if (Auth::check())
<!-- 已登入 -->
@else
<!-- 未登入 -->
@endif
Laravel 允許自訂 directive,自訂常用的判斷式。
開啟 /app/Providers/AuthServiceProvider.php 並在 boot() 中加入以下設定:
// Illuminate\Support\Facades\Blade;
Blade::if('isLoggedIn', function() {
return Auth::check();
});
之後,就可以在 Blade 中使用自訂判斷:
@isLoggedIn
<!-- 已登入 -->
@else
<!-- 未登入 -->
@endisLoggedIn
PostgreSQL 中,要查詢 item 是否在 JSON list (array) 中的語法是:
where user_list::jsonb ? 'user name'
如果使用 DB:raw() 代入 Laravel Eloquent 會出現錯誤訊息:
-- where(DB::raw('user_list::jsonb ? \'user name\''))->get()
SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "$1"
原因是 ? 會被視為 prepare/binding 的記號,上面語法沒有給定 bind 條件,所以發生錯誤。
若不使用 prepare/binding,則要 ? escape 為 ??:
-- where(DB::raw('user_list::jsonb ?? \'user name\''))->get()
Illuminate\Database\Eloquent\Collection {#6157
....
}
把 Laravel Queue 中提到的 method 列出來,幾乎都會用到的是這幾個:
handle()fail()retryUntil()backoff()class MyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct($jobData)
{
$this->jobData = $jobData;
}
public function handle()
{
// work
}
public function fail(Throwable $e = null)
{
// job failed 時要做的事情
}
public function retryUntil()
{
return now()->addHours(2);
}
public function backoff()
{
// 下一次 retry 中間要間格多少時間
return [30, 60, 120];
}
}
應該還有一些文件上沒寫到的,可能要去翻影片才知道。