CakePHP4の「bake model」コマンドのオプションまとめ
bakeコマンドを使ってコントローラやモデルのクラスを生成することができます。
非常に便利ですが、例えばテーブルがCakePHPの規約に準拠していない場合など、オプションを使うことで更に柔軟な対応ができるようになります。
今回は「bake model」コマンドのオプションについて自分なりに調べた内容をまとめます。
まずは以下のコマンドを使ってどのようなオプションがあるのかを確認してみます。
$ ./bin/cake bake model --help
Bake table and entity classes.
Usage:
cake bake model [options] []
Options:
--connection, -c The datasource connection to get data from.
(default: default)
--display-field The displayField if you would like to choose one.
--fields A comma separated list of fields to make
accessible.
--force, -f Force overwriting existing files without
prompting.
--help, -h Display this help.
--hidden A comma separated list of fields to hide.
--no-associations Disable generating associations.
--no-entity Disable generating an entity class.
--no-fields Disable generating accessible fields in the
entity.
--no-fixture Do not generate a test fixture skeleton.
--no-hidden Disable generating hidden fields in the entity.
--no-rules Disable generating a rules checker.
--no-table Disable generating a table class.
--no-test Do not generate a test case skeleton.
--no-validation Disable generating validation rules.
--plugin, -p Plugin to bake into.
--primary-key The primary key if you would like to manually set
one. Can be a comma separated list if you are
using a composite primary key.
--quiet, -q Enable quiet output.
--table The table name to use if you have
non-conventional table names.
--theme, -t The theme to use when baking code.
(choices: Bake|Migrations)
--verbose, -v Enable verbose output.
Arguments:
name Name of the model to bake (without the Table suffix). You can use
Plugin.name to bake plugin models. (optional)
Omitting all arguments and options will list the table names you can
generate models for.
上記のヘルプの通りなのですが、「options」のところに様々なオプションが指定できます。
日本語にしつつ、どのような使い方ができるのかをみていきましょう。
なお、以降の説明で登場する「companies」テーブルと「employees」テーブルは、以下の構造になっている前提です(データベースはMariaDBを使用)。
> desc companies;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
> desc employees;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| company_id | int(11) | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
※「employees」テーブルの「company_id」カラムが「companies」テーブルの主キー「id」の外部キー。
「–connection」「-c」オプション
接続するデータベースの指定。
app.php(開発環境ではapp_local.php)の「Datasources」内で、接続DBの情報を指定するのですが、このオプションを指定しないと「default」で指定しているデータベースに接続してbake modelを実行します。変更したい場合は、app.phpの内容を追加・修正しましょう。「default」以外の設定がある場合、オプションでそれを指定すればそちらのデータベースに接続してbakeを実行します。
return [
~省略~
'Datasources' => [
'default' => [
'host' => 'ホスト名',
/*
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
//'port' => 'ポート番号',
'username' => '接続ユーザ名',
'password' => '接続パスワード',
'database' => '接続データベース名',
/**
* If not using the default 'public' schema with the PostgreSQL driver
* set it here.
*/
//'schema' => 'myapp',
/**
* You can use a DSN string to set the entire configuration
*/
'url' => env('DATABASE_URL', null),
],
~省略~
]
~省略~
]
大抵の場合はインストール時点でdefaultの設定を変更することが多いと思うので、
このオプションを使う機会はあまり多くないと思われます。
「–display-field」オプション
「find(‘list’)」メソッドを使ってレコードを取得した際にvalueになる部分を指定するオプション。
デフォルトでは「name」フィールドが指定されるようですが、それを変更したい時に指定します。
例えば、次のコマンドでEmployeesTableクラスを作成すると、
./bin/cake bake model --display-field company_id Employees
initializeメソッドに「$this->setDisplayField(‘company_id’);」の記述が入ります。
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('employees');
$this->setDisplayField('company_id'); //←この部分が記載される
$this->setPrimaryKey('id');
$this->belongsTo('Companies', [
'foreignKey' => 'company_id',
]);
}
「–force」,「-f」オプション
既にモデルを使用していた場合に強制上書きをするオプション
「–help」,「-h」オプション
上記で使用したようにヘルプを表示するオプション
Entityクラスの$_hiddenに指定するプロパティ名を指定するオプション。
複数ある場合はカンマ区切りで指定します。例えばユーザ情報のパスワードをこのhiddenに指定することが多いです。
ただ、passwordカラムは自動でhiddenに設定されるので、オプションを指定しなくても以下の記述が追加されます。
protected $_hidden = [
'password',
];
次のコマンドで「Companies」モデルを生成してみると、
./bin/cake bake model --hidden name Companies
Company.phpに以下の記述が入ります。
protected $_hidden = [
'name',
];
$_hidden属性が指定されると、コントローラなどでエンティティを使用したときにその属性を取得できなくなります。
「–no-associations」オプション
関連を生成しないオプション。
例えば、「Company」と「Employee」の関連は、「Company hasMany Employees」「Employee belongsTo Company」なので、
「EmployeesTable」クラスには、次の記述が入り、
public function initialize(array $config): void
{
~省略~
$this->belongsTo('Companies', [
'foreignKey' => 'company_id',
]);
}
「CompaniesTable」クラスには、次の記述が入ります。
public function initialize(array $config): void
{
~省略~
$this->hasMany('Employees', [
'foreignKey' => 'company_id',
]);
}
この関連の記述を生成しないのが、–no-associationsオプションになります。
「–no-entity」オプション
Entityクラスを生成しないオプション。
「–no-fields」オプション
アクセス可能なフィールドを生成しないオプション。
例えば「Employee」エンティティを生成すると、次のように$_accessible変数にフィールド用の配列がセットされますが、
これを指定しない場合(後で自分で設定したい場合など)に指定します。
class Employee extends Entity
{
protected $_accessible = [
'name' => true,
'company_id' => true,
'company' => true,
];
}
「–no-fixture」オプション
テスト用のデータを指定するfixtureファイルを生成しない時に指定するオプション。
先ほどの「–hidden」オプションの説明でも登場したEntity内のhiddenフィールドを生成しないオプション。
「–no-rules」オプション
ルールチェッカーの生成をしないオプション。
デフォルトでは以下のようにbuildRulesメソッドが作成されます(以下はEmployeesTableの例)。
public function buildRules(RulesChecker $rules): RulesChecker
{
$rules->add($rules->existsIn(['company_id'], 'Companies'), ['errorField' => 'company_id']);
return $rules;
}
「–no-rules」オプションを指定するとこのメソッドを作成しなくなります。
「–no-table」オプション
Tableクラスを生成しないオプション。
「–no-test」オプション
テストケースを生成しないオプション。
このオプションを指定しないと、自動で各Tableクラス用にテストファイルが作成されます。
「–no-validation」オプション
バリデーションルールを生成しないオプション。
このオプションを指定しない場合、例えば「EmployeesTable」クラスだと以下のvalidationDefaultメソッドが生成されます。
public function validationDefault(Validator $validator): Validator
{
$validator
->integer('id')
->allowEmptyString('id', null, 'create');
$validator
->scalar('name')
->maxLength('name', 255)
->allowEmptyString('name');
return $validator;
}
「–plugin」, 「-p」オプション
モデルのプラグインを生成するオプション。
CakePHPではプラグインを作成し、別の色々な箇所で使用することができます。
私はプラグイン作成をしたことがありませんが、そのプラグインのモデルのデフォルトを生成してくれるオプションのようです。
「–primary-key」オプション
主キーをデフォルトとは異なるものにしたい場合に使用するオプション。
複合主キーを指定する場合は、カンマ区切りで複数のフィールドを指定する。
Tableクラスで「$this->setPrimaryKey(‘フィールド名’);」で主キーフィールドを指定できる。
「EmployeesTable」クラスの場合、以下のようになる。
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('employees');
$this->setDisplayField('company_id');
$this->setPrimaryKey('id'); //←この部分
$this->belongsTo('Companies', [
'foreignKey' => 'company_id',
]);
}
「–quiet」, 「-q」オプション
コマンド実行時の出力を行わないオプション。
あってもなくても生成されるファイルは変わらない。
「–table」オプション
規約と異なるテーブル名を使用する場合にテーブル名を指定するオプション。
詳細はこちらの記事にまとめています。
「–theme」,「-t」オプション
Bakeするときのテーマを指定するオプション。デフォルトでは「Bake」か「Migrations」を指定。
Migrationsの方を指定してみましたが、作成されたTableクラスとEntityクラスはオプション無のものと同様だったので、違いについては分かりませんでした。
Bakeコマンドで作成されるファイルは、今まで見てきたようにデフォルトでどのように生成されるかが決まっています。私は作成したことがありませんが、その生成結果を独自テーマを作成してカスタマイズすることができるようです。このオプションを指定することで、そのテーマを指定することができるのかと思われます。
「–verbose」, 「-v」オプション
コマンド実行時の標準出力を行うオプション。–quietの逆。
デフォルトで標準出力されるので、内容は変わらないように思います(もしかしたら詳細に表示されるのかもしれませんが)。
以上helpで表示されたオプションの内容でした。
特にオプション指定せずに後で変更しても問題ありませんが、オプションを押さえておくことで、モデルクラスの中身の意味が分かるようになりました。