Skip to content

從 PHP 與 Laravel 到 Ruby

Recorder:polyglot PHP adapter(函式與 static 方法透過產生的 driver 呼叫)。Laravel 路由(Route::get)會由 analyze 找出。

從 Laravel 到 Rails(兩者是近親)

Laravel Rails
routes/web.php、routes/api.php config/routes.rb(保留 /api 前綴)
Controller + Request $request controller action + params
return response()->json($x, 201) render json: x, status: :created
abort(404) / firstOrFail() head :not_found / find_by! + rescue_from,並搭配錄製下來的 body
Blade(@extends、@section、@foreach、{{ }}) ERB layout(yield/content_for)、each、<%= %>(frontend.md)
Eloquent model、relation、scope、cast ActiveRecord model、association、scope、attribute/serializer
Migration Rails migration,但先沿用既有的資料表(ADR)
Form Request / $request->validate([...]) model 驗證或 form object
Middleware before_action / Rack middleware
Queue / Job Active Job + Solid Queue
Mailable Action Mailer
config() / .env config/*.yml、credentials、ENV
Sanctum / Breeze 驗證 Rails authentication generator;bcrypt 雜湊可以沿用($2y$ -> $2a$)

語法結構

  • 錯誤:InvalidArgumentException -> ArgumentError;DivisionByZeroError -> ZeroDivisionError;RuntimeException -> RuntimeError;應用程式自己的例外保留原名。
  • 陣列是有序的 map:鍵為 0..n-1 的 PHP 陣列是 JSON list;若鍵有缺口(在 unset 或 array_filter 之後),就會變成 JSON object。在錄製結果顯示為 list 的地方,請使用 array_values 的語意(values)。
  • null -> nil;isset($a['k']) -> a.key?("k") && !a["k"].nil?;empty($x) 對 0、"0"、""、[]、null 都是 true。
  • 字串:strlen 計算的是位元組(bytesize);mb_strlen 計算的是字元(length)。. 串接 -> 字串插值。

陷阱

  • 寬鬆比較(==、未開 strict 的 in_array):"1" == 1、"abc" == 0(PHP 7)。在錄製案例依賴型別轉換的地方,請明確移植這個轉換。
  • 四捨五入:round(2.5) == 3 且 round(-2.5) == -3(遠離零進位),和 Ruby 的 round 一樣。intdiv 向零截斷;% 的正負號跟隨被除數(remainder);/ 在整除時回傳整數(4 / 2 === 2),否則回傳浮點數。
  • 整數溢位會悄悄變成浮點數。
  • json_encode 預設會把 / 跳脫為 \/、把 unicode 跳脫為 \uXXXX:body 文字會不同,但解析後的 JSON 相同(重播比對的是解析後的 JSON)。
  • PHP 8 之前,sort、usort 不是穩定排序。
在 GitHub 上編輯此頁 →