New CakePHP 4.0 Strawberry.

  • 2020年7月8日
  • 2020年7月8日
  • PHP, CakePHP
  • 1473view
PHP

どうもカトーです。

最近はLaravelが人気ですが、業務でCakePHP触る事があり、調べてみると随分前にCakePHPもバージョン4、CakePHP 4.0 Strawberry.が出ていることに気がつきましたよ。最近は社長業務で開発もしてなかったのこともありますので、このままじゃマズイので、早速手元の環境で簡単なBAKEしてみます。こちらはその記録ですよ。

 

まずはダウンロードとセットアップ

公式よると動作環境は、

  • HTTP Server. For example: Apache. Having mod_rewrite is preferred, but by no means required. You can also use nginx, or Microsoft IIS if you prefer.
  • Minimum PHP 7.2 (7.4 supported).
  • mbstring PHP extension
  • intl PHP extension
  • simplexml PHP extension
  • PDO PHP extension

今回、手元のXAMPPで動かすので、PHPのバージョンだけでも確認しておきます。

# php -v
PHP 7.4.7 (cli) (built: Jun  9 2020 13:36:15) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies

詳しくはこちら
https://book.cakephp.org/4/en/installation.html

laravelと同じ用にcomposerから落とします。

# composer create-project --prefer-dist cakephp/app:~4.0 my_app_name
Installing cakephp/app (4.1.1)
  - Installing cakephp/app (4.1.1): Loading from cache
Created project in my_app_name
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for cakephp/cakephp ~4.1.0 -> satisfiable by cakephp/cakephp[4.1.0].
    - cakephp/cakephp 4.1.0 requires ext-intl * -> the requested PHP extension intl is missing from your system.
  Problem 2
    - cakephp/debug_kit 4.1.0 requires cakephp/cakephp ^4.0 -> satisfiable by cakephp/cakephp[4.1.0].
    - cakephp/debug_kit 4.1.1 requires cakephp/cakephp ^4.0 -> satisfiable by cakephp/cakephp[4.1.0].
    - cakephp/debug_kit 4.1.2 requires cakephp/cakephp ^4.0 -> satisfiable by cakephp/cakephp[4.1.0].
    - cakephp/debug_kit 4.1.3 requires cakephp/cakephp ^4.0 -> satisfiable by cakephp/cakephp[4.1.0].
    - cakephp/debug_kit 4.2.0 requires cakephp/cakephp ^4.0 -> satisfiable by cakephp/cakephp[4.1.0].
    - cakephp/cakephp 4.1.0 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - Installation request for cakephp/debug_kit ^4.1 -> satisfiable by cakephp/debug_kit[4.1.0, 4.1.1, 4.1.2, 4.1.3, 4.2.0].

  To enable extensions, verify that they are enabled in your .ini files:
    - D:\xampp\php\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

ガンガンエラー出てます。

ひとつずつ直していきます。
エラーを見ると、requires ext-intl * -とありますので、php.iniでextension=intlの行を有効にします。

extension=gettext
;extension=gmp
extension=intl
;extension=imap
;extension=ldap

再度ディレクトリーを消して、Webサービスを再起動して再度コマンドを打ちます。

# composer create-project --prefer-dist cakephp/app:~4.0 my_app_name
Installing cakephp/app (4.1.1)
  - Installing cakephp/app (4.1.1): Loading from cache
Created project in my_app_name
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 85 installs, 0 updates, 0 removals
  - Installing cakephp/plugin-installer (1.2.0): Downloading (100%)
  - Installing psr/simple-cache (1.0.1): Downloading (100%)
  - Installing psr/log (1.1.3): Downloading (100%)

----(省略)------

  - Installing phpunit/php-code-coverage (7.0.10): Loading from cache
  - Installing doctrine/instantiator (1.3.1): Downloading (100%)
  - Installing phpdocumentor/reflection-common (2.2.0): Downloading (100%)
  - Installing webmozart/assert (1.9.0): Downloading (100%)
  - Installing phpdocumentor/type-resolver (1.3.0): Downloading (100%)

----(省略)------

Set Folder Permissions ? (Default to Y) [Y,n]? y
Updated Security.salt value in config/app_local.php

早速、localhostで確認してみます。

無事に入ったようです。

トップに、

Please be aware that this page will not be shown if you turn off debug mode unless you replace templates/Pages/home.php with your own version.

デバッグモードをオフにすると、templates / Pages / home.phpを独自のバージョンに置き換えない限り、このページは表示されないことに注意してください。(自動翻訳】

なにか色々変わっているのか不明ですが、まずは目的通りCRUDを用意してみます。

CakePHP4 初期設置

configディレクトリの.env.exampleを.envにリネームし、各種設定をします。

export APP_NAME="MyBlog"
export DEBUG="true"
export APP_ENCODING="UTF-8"
export APP_DEFAULT_LOCALE="ja_JP"
export APP_DEFAULT_TIMEZONE="Asia/Tokyo"
export SECURITY_SALT="otsusuORAGOKUU!omeeeYoeeena!"

SECURITY_SALTには任意の文字列を入れておきます。続けて、デフォルトではenvファイルは読み込まれないので、bootstrap.phpのファイルのコメントアウトされている部分有効にします。

/config/bootstrap

if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
    $dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
    $dotenv->parse()
        ->putenv()
        ->toEnv()
        ->toServer();
}

次に、ローカル環境の場合、app_local.phpにデータベース接続の設定をします。
今回は、確認なので、デフォルトのmy_app secretの部分を確認してMySQLへ設定します。
※注意 当然ですが、ちゃんとした運用にはパスワードも変更は必須ですよ。

    'Datasources' => [
        'default' => [
            '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',
            /**


XAMPPだとadminからphpMyAdmin入ってるので、そのままユーザーを追加。

 

 


ここでアクセスできているのを確認です。

データベースの設定

CakePHPではマイグレーション機能でデータベース構造を作成することができるので、早速実行してみます。

# bin\cake bake migration CreatePosts

Creating file D:パスですね\config\Migrations\20200706081624_CreatePosts.php

この辺は過去触ったバージョンを変わりがないようですね。安心しました。

ちなみに、’bin’ は、内部コマンドまたは外部コマンド、操作可能なプログラムまたはバッチ ファイルとして認識されていません。と出た場合は/スラッシュを¥マークのバックスラッシュしましょう。ついWindows環境だとハマってモジール入れ直しせずにどうぞ。

早速、できた20200706081624_CreatePosts.phpを加工してデータベース構造を用意します。

 

    public function change()
    {
        $table = $this->table('posts');
        $table
        ->addColumn('title', 'text')
        ->addColumn('body', 'text')
        ->addColumn('created', 'datetime')
        ->addColumn('modified', 'datetime');
        $table->create();
    }

 

# bin\cake migrations migrate

--(略)----
ordering by creation time

 == 20200706081624 CreatePosts: migrating
 == 20200706081624 CreatePosts: migrated 1.5426s

All Done. Took 1.5443s
--(略)----
Dump file `パス\my_app_name\config\Migrations\schema-dump-default.lock` was successfully written

 

ちゃんとできてるようで、問題ないようですね。

 

Bakeの確認

この4になってなにか違うのか一応Bakeを確認します。

#bin\cake bake  --help

---(略)------+--

Bake:
 - bake all
 - bake behavior
 - bake cell
 - bake command
 - bake component
 - bake controller
 - bake controller all
 - bake fixture
 - bake fixture all
 - bake form
 - bake helper
 - bake mailer
 - bake middleware
 - bake model
 - bake model all
 - bake plugin
 - bake shell
 - bake shell_helper
 - bake task
 - bake template
 - bake template all
 - bake test

Migrations:
 - bake migration
 - bake migration_diff
 - bake migration_snapshot
 - bake seed

To run a command, type `cake command_name [args|options]`
To get help on a specific command, type `cake command_name --help`

久しぶりに触ったのですが同じ用にいけそうなので、そのままBakeします。

# bin\cake bake  all posts
Bake All
-------------------------------------------------------------------------------
One moment while associations are detected.
Baking table class for Posts...

--(略)---
`
Bake All complete.

 

問題ないようです。

ちゃんとPOSTできますね。

 

躓いたこと

さらっと書いたのですが、久しぶりに触ったので、実は以下、躓きましたよ。

  • app_local.phpの利用
  • デフォルトではenvファイルは読み込まれないので、bootstrap.phpのファイル修正
  • Windows環境でスラッシュとバックスラッシュ
  • 途中で仮想でもいいから、やっぱりLinuxサーバ立てようと悶絶

やはり定期的にphpフレームワークは触らないとだめですね。早速次回はこのまま何か作ろうと思いますよ。

 

最新情報をチェックしよう!
>システム構築・保守に特化した会社です。

システム構築・保守に特化した会社です。

システムの構築・保守運用「システムガーディアン」 社内システム担当が欲しいが、専属で雇うほどの仕事量はない。 必要な時に必要なだけ頼りたいというお悩みを持つ企業様へ専門知識を持って対応を行っております。 サーバから各種システムまで自社・他社で構築されたシステムに対してサポートを行っております。

CTR IMG