【CakePHP入門】bakeの使い方

こんにちは!フリーエンジニアのせきです。

CakePHPには、データベースのテーブルに合わせてModel、Template、Controllerの雛形を自動生成してくれるbakeという便利な機能があります。

この記事では、

・bakeとは何か知りたい
・bakeの使い方を知りたい

という基本的な内容から、

・コードを一括作成する方法を知りたい

といった応用的な内容に関しても解説していきます。

今回はそんなbakeの使い方について、わかりやすく解説します!

目次

bakeとは

bakeとは、CakePHPのMVCモデルによるWebアプリケーションの雛形を自動生成するための機能です。

MVCモデルとはWebアプリケーションのデザインパターンで、アプリケーションを以下の3つの役割に分割します。

  • Model アプリケーションのデータとビジネスロジックを持つ
  • View ユーザインターフェイスを生成する
  • Controller ユーザからのリクエストを受け取り、ModelとViewを使いレスポンスを返す

bakeは指定したテーブルに対しこれら3つの部品を生成し、そのテーブルへのCRUD機能を持つWebアプリケーションを作成します。

CRUD機能とは、Create(生成)、Read(読み取り)、Update(更新)、Delete(削除)機能です。

bakeはCakePHP1.Xからある機能ですが、CakePHP3.Xからいくつか仕様が変わっています

大きな違いに、以下のようなものがあります。

  • bakeを実行するcakeコマンドのパスが変更
  • bakeの実行方法が対話式の実行から、パラメータを指定して実行する方式に変更
  • ユーザインターフェイスの生成部分は、ViewではなくTemplate

この記事では、CakePHP3.Xのbakeの使い方について解説していきます。

bakeの使い方

事前準備

bakeを使用するには、CakePHPのインストールが完了している必要があります。

bakeはcakeコマンドから実行しますが、cakeコマンドのパスは「[プロジェクトのパス]/bin」になります。

CakePHP3.Xから変更されていますので、注意してください。

以下のようにcakeコマンドを実行すると、bakeの機能一覧が表示されます。

cake bake

以下は、プロジェクトのパスが「C:\xampp\htdocs\cakephp\cake3_test\bin」である場合の実行結果です。

The following commands can be used to generate skeleton code for your application.

Available bake commands:

- all
- behavior
- cell
- command
- component
- controller
- fixture
- form
- helper
- mailer
- middleware
- migration
- migration_diff
- migration_snapshot
- model
- plugin
- seed
- shell
- shell_helper
- task
- template
- test
- twig_template

By using `cake bake [name]` you can invoke a specific bake task.

bakeコマンドを引数なしで実行すると、bakeで実行可能な引数の一覧が表示されます。

Windows、Linux、Macともに、使い方は同じです。

次に、使用するデータベースの設定とテーブルの作成を行います。

データベースの設定は、「[プロジェクトのパス]/config/app.php」で行います。

-省略-
'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',	// ドライバ
        'persistent' => false,
        'host' => 'localhost',	// ホスト名
        /**
         * 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' => 'non_standard_port_number',	// ポート
        'username' => 'my_app',	// ユーザー名
        'password' => 'secret', // パスワード
        'database' => 'my_app', // データベース名
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,
-省略-

ドライバ、ホスト名、ポート、ユーザ名、パスワード、データベース名等、使用するデータベースの設定に変更します。

今回アプリケーションを作成するテーブルとして、ユーザ情報を管理するUSERSテーブルを用意します。

CREATE TABLE USERS
(
	ID INT NOT NULL AUTO_INCREMENT,
	NAME VARCHAR(32),
	ADDRESS VARCHAR(32),
	AGE INT,
	COMPANY_ID INT,
	PRIMARY KEY (ID)
);

Modelの作成

以下のコマンドを実行すると、作成できるModelの一覧が表示されます。

cake bake model

以下は、設定したデータベースにUSERSテーブルとCOMPANYテーブルがある場合の実行結果です。前章で作成したUSERSテーブルに加えてCOMPANYテーブルが追加してあります。

Choose a model to bake from the following:
- COMPANY
- USERS

今回はUSERSテーブルに対してアプリケーションを作成していきますので、以下を実行します。

cake bake model users

実行結果

One moment while associations are detected.

Baking table class for Users...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Model\Table\UsersTable.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Table\UsersTable.php`
Deleted `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Table\empty`

Baking entity class for User...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Model\Entity\User.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Entity\User.php`
Deleted `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Entity\empty`

Baking test fixture for Users...

Creating file C:\xampp\htdocs\cakephp\cake3_test\tests\Fixture\UsersFixture.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\tests\Fixture\UsersFixture.php`
Deleted `C:\xampp\htdocs\cakephp\cake3_test\tests\Fixture\empty`
Bake is detecting possible fixtures...

Baking test case for App\Model\Table\UsersTable ...

Creating file C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Model\Table\UsersTableTest.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Model\Table\UsersTableTest.php`

これでModelが作成されます。

データベースに接続できない場合はエラーが発生します。

その場合は、「[プロジェクトのパス]/config/app.php」のデータベース設定が正しいか、php.iniで使用するドライバのモジュールが有効になっているかを確認してください。

Templateの作成

次にTemplateの作成を行います。

以下を実行します。

cake bake template users

実行結果

Baking `index` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\index.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\index.ctp`

Baking `view` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\view.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\view.ctp`

Baking `add` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\add.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\add.ctp`

Baking `edit` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\edit.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\edit.ctp`

Contorollerの作成

次にContorollerの作成を行います。

以下を実行します。

cake bake controller users

実行結果

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Controller\UsersController.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Controller\UsersController.php`
Bake is detecting possible fixtures...

Baking test case for App\Controller\UsersController ...

Creating file C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Controller\UsersControllerTest.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Controller\UsersControllerTest.php`

作成されたアプリケーションの確認

自動生成されたアプリケーションを確認していきます。

http://[サーバ名]/[プロジェクト名]/users」にアクセスします。

bake後のUSERS画面

USERSテーブルの内容が一覧表示されます。今はデータがないのでテーブルに何も表示されていません。

New Userをクリックすると新規ユーザー登録画面に遷移します。これがCRUDのC(Create)に該当します。

ユーザー情報登録画面

ユーザーを追加してからList Usersをクリックすると最初の一覧画面に遷移します。今回はユーザー情報を追加したので、テーブルにその情報が表示されています。
テーブルのAction列にあるView, Edit, Deleteを選択することで、表示編集削除もできます。
これらがCRUDのRead, Update, Deleteにそれぞれ対応しています。

ユーザー登録後のUSERS画面

allコマンドで一括作成する

ここまではModel、Template、Controllerを個別に作成していましたが、これら3つを一括で作成することもできます

以下を実行します。

cake bake all users

個別に作成するのと、全く同じものが作成されます。

実行結果

Bake All
---------------------------------------------------------------
One moment while associations are detected.

Baking table class for Users...

File `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Table\UsersTable.php` exists
Do you want to overwrite? (y/n/a/q)
[n] > y
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Table\UsersTable.php`

Baking entity class for User...

File `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Entity\User.php` exists
Do you want to overwrite? (y/n/a/q)
[n] > y
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Model\Entity\User.php`

Baking test fixture for Users...

File `C:\xampp\htdocs\cakephp\cake3_test\tests\Fixture\UsersFixture.php` exists
Do you want to overwrite? (y/n/a/q)
[n] > a
Wrote `C:\xampp\htdocs\cakephp\cake3_test\tests\Fixture\UsersFixture.php`
Bake is detecting possible fixtures...

Baking test case for App\Model\Table\UsersTable ...

Creating file C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Model\Table\UsersTableTest.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Model\Table\UsersTableTest.php`

Baking controller class for Users...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Controller\UsersController.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Controller\UsersController.php`
Bake is detecting possible fixtures...

Baking test case for App\Controller\UsersController ...

Creating file C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Controller\UsersControllerTest.php
Wrote `C:\xampp\htdocs\cakephp\cake3_test\tests\TestCase\Controller\UsersControllerTest.php`

Baking `index` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\index.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\index.ctp`

Baking `view` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\view.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\view.ctp`

Baking `add` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\add.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\add.ctp`

Baking `edit` view template file...

Creating file C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\edit.ctp
Wrote `C:\xampp\htdocs\cakephp\cake3_test\src\Template\Users\edit.ctp`
Bake All complete.

今回は、すでにbakeを実行していたフォルダに対してbake allを行ったので、Do you want to overwrite? (y/n/a/q)のように上書きの確認が表示されました。

それぞれy=yes、n=no、a=全てyesとする、q=bakeコマンドを中断するという意味なので、必要に応じてキーボードから入力してください。

まとめ

今回はbakeの使い方について解説しました。

bakeを使うと、MVCモデルによるWebアプリケーションがとても簡単に作成できます。

bakeの使い方を忘れてしまったら、この記事を思い出して下さい!

この記事を書いた人

フリーランスでWebシステム開発やゲーム開発をしています。
読者の方にプログラミングの面白さをお伝えしたいです。

目次