LoginSignup
8
4

More than 5 years have passed since last update.

CakePHP 2.8 で rails console な REPL 開発環境を作る

Last updated at Posted at 2018-06-02

概要

rubyにはbinding.pry(pry-byebug) というREPLがあって、コンソール開発のスピードを超絶加速してくれます。それの php 版です。ステップ実行とかはできないのですが、バッチの開発や、TDDでコンソールのみで開発出来る範囲ならとっても早いです。debug()とはサヨナラ。ちなみに、CakePHP3系ではデフォで入ってるみたいです。

導入手順

psysh の導入

composer で psysh を追加します。

// composer.json
"psy/psysh": "^0.8.14"

インストール

$ ./composer.pher install

breakpoint() 関数を実装

CakePHP3系に習って、breakpoint()関数を作ります。
bootstrap.php でも、最適なファイルで利用ください。僕は、Libs/Debugger.phpに設置してます。

<?php

class Debugger
{
    /**
     * Command to return the eval-able code to startup PsySH in interactive debugger
     * Works the same way as eval(\Psy\sh());
     * psy/psysh must be loaded in your project
     * @link http://psysh.org/
     * ```
     * eval(\Debugger::breakpoint());
     * ```
     * CakePHP3では標準導入されてます。
     * @link https://github.com/cakephp/cakephp/blob/d92d4f5f3ca4f2513dd5a8fdab6a1bdb4735af9f/src/basics.php#L103
     * @return string
     */
    public static function breakpoint()
    {
        if ((PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') && class_exists('\Psy\Shell')) {
            // `$this`がnullになってしまうので、
            // 明示的に `$t` に値を格納する形をとってる。
            return 'extract(\Psy\debug(array_merge_recursive(get_defined_vars(), array("t" => $this)), $this));';
        }
        trigger_error(
            'psy/psysh must be installed and you must be in a CLI environment to use the breakpoint function',
            E_USER_WARNING
        );
    }
}

これで、コード中に eval(\Debugger::breakpoint()); を入れることでブレークポイントを仕込んで開発ができます。
が、今回は rails console がゴールなので、さらに。

シェルを作る


/**
 * コンソールでプログラミング出来る
 *
 * 実行
 * `$ /path/to/Console/cake console`
 */
class ConsoleShell extends AppShell
{

    function main()
    {
        eval(\Debugger::breakpoint());
    }
}

$ ./Console/Cake console で実行できます。

$ ./Console/cake console

Welcome to CakePHP v2.8.9 Console
---------------------------------------------------------------

Psy Shell v0.8.14 (PHP 5.3.29  cli) by Justin Hileman
New version is available (current: v0.8.14, latest: v0.9.4)

From Console/Command/ConsoleShell.php:16:

    14|     function main()
    15|     {
  > 16|         eval(\Debugger::breakpoint());
    17|     }
    18| }

>>> list
Variables: $t, $this
>>> $user = ClassRegistry::init('User')
$user = ClassRegistry::init('User')
>>> $u = $user->findById(1)
>>> $u['User']['name'] = 'hogehgoe'
>>> $user->save($u)

といった形で、簡単に実装を確認できます。

その他

psyshコンソール内に標準装備の関数があります。

list で今展開されてる変数一覧見れます

>>> list
Variables: $a, $t, $this, $U, $user, $User

show クラス名 で該当クラスを開けます

>>> show Model
  >   45| class Model extends Object implements CakeEventListener {
      46|
      47| /**
      48|  * The name of the DataSource connection that this Model uses
      49|  *
      50|  * The value must be an attribute name that you defined in `app/Config/database.php
      51|  * or created using `ConnectionManager::create()`.
      52|  *
      53|  * @var string
      54|  * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
      55|  */
      56|       public $useDbConfig = 'default';

おしまい

ブレークポイントを入れて動作確認できるだけでも十分はかどりますが、コンソールがあると気軽に実装確認もできるので、参考になれば嬉しいです。

8
4
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
8
4