0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

$ を書きたくなくてPHPをS式から生成するトランスパイラをRacketで書いた

0
Last updated at Posted at 2026-04-23

PHPの $ を一日に何百回タイプしているか、数えたことがあるだろうか。

私は、近年LaravelなどPHPの仕事をやる機会が多い。
Laravelは素晴らしいフレームワークだし、PHPも以前より良い言語になってきた。
PHPが嫌いなわけじゃない。
しかし最近私は$ $this->を書くことに疲弊していた。

そんなある日閃いた。
「大好きなS式からPHPに変換すれば$ $this->書かなくてもいいのではないか?」
そこで日常的私がよく使っているRacketでPHPトランスパイラを作ってみた。

Racketは、Schemeから派生した言語で、言語を作るための言語である。
他のSchemeやLispでも良かったが、今回一番身近なRacketを使った。

作ったトランスパイラに下のようなコードを入れると、

(program
   (namespace (ns App Http Controllers))
   (use (ns App Models User))
   (use (ns Illuminate Http Request))

   (class UserController #:extends Controller
     (method (public) index ((param/type Request request))
       (expr-stmt
        (assign = (var users)
                (call (:: User all))))
       (return
        (call view "users.index"
              (call compact "users"))))

     (method (public) show ((param/type int id))
       (expr-stmt
        (assign = (var user)
                (call (:: User findOrFail) (var id))))
       (return
        (call view "users.show"
              (call compact "user"))))))

こんなPHPに変換されます。

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = User::all();
        return view('users.index', compact('users'));
    }
    public function show(int $id)
    {
        $user = User::findOrFail($id);
        return view('users.show', compact('user'));
    }
}

「安全に書けるようになったか?」とか「簡単に書けるようになったか?」とかはおいておいて、
$を4つ書かなくてもよくなった。
目標達成である。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?