php artisan tinker の使い方

Why?

  • Laravel チュートリアルやってて、突然出現した
  • pryっぽいけど、なにができるのか疑問

What?

  • https://github.com/laravel/tinker
  • REPL (Read-Eval-Print Loop) 。対話的シェル。
    • Ruby の pry と似たもの
    • 初めての言語を試しに(とりま、echoしたいとか)触りたいときとかに便利
    • 対話的にデバッグするときに便利
  • コンソールにどういう状況のものが表示されるのか?
    • 再起動するまで変数値などは保存される。再起動したら、変数とかがリセットされる。
    • モデルとかを使うときは、立ち上げ時のコードの状態が反映されているので、コードをいじったらコード反映のために再起動する必要がある
    • デバッグのときは、ブレークポイントの状態のものが表示される。
  • ラッパー

How to use?

  • プロジェクトディレクトリ内で $ php artisan tinker すると立ち上がる。
$ php artisan tinker
Psy Shell v0.8.1 (PHP 7.1.1-1+deb.sury.org~xenial+1 — cli) by Justin Hileman

New version is available (current: v0.8.1, latest: v0.8.2)
>>>
  • phpコマンドを逐次実行できる (hogeは標準出力、=> nullは返り値)
>>> echo "hoge";
hoge⏎
=> null
  • tinderコマンドは色々ある
>>> help
  help             Show a list of commands. Type `help [foo]` for information about [foo].      Aliases: ?
  ls               List local, instance or class variables, methods and constants.              Aliases: list, dir
  dump             Dump an object or primitive.
  doc              Read the documentation for an object, class, constant, method or property.   Aliases: rtfm, man
  show             Show the code for an object, class, constant, method or property.
  wtf              Show the backtrace of the most recent exception.                             Aliases: last-exception, wtf?
  whereami         Show where you are in the code.
  throw-up         Throw an exception out of the Psy Shell.
  trace            Show the current call stack.
  buffer           Show (or clear) the contents of the code input buffer.                       Aliases: buf
  clear            Clear the Psy Shell screen.
  history          Show the Psy Shell history.                                                  Aliases: hist
  exit             End the current session and return to caller.                                Aliases: quit, q
  clear-compiled   Remove the compiled class file
  down             Put the application into maintenance mode
  env              Display the current framework environment
  migrate          Run the database migrations
  optimize         Optimize the framework for better performance
  up               Bring the application out of maintenance mode
  inspire          Display an inspiring quote
>>> ls -gl

Global Variables:
  $app                         Illuminate\Foundation\Application {#3 …15}
  $argc                        2
  $argv                        [ …2]
  $GLOBALS                     [ …13]
  $input                       Symfony\Component\Console\Input\ArgvInput {#20}
  $kernel                      App\Console\Kernel {#22}
  $_COOKIE                     []
  $_FILES                      []
  $_GET                        []
  $_POST                       []
  $_REQUEST                    []
  $_SERVER                     [ …35]
  $__composer_autoload_files   [ …8]

参照