5
2

More than 1 year has passed since last update.

CodeIgniter 4 導入メモ

Posted at

はじめに

CodeIgniter 4 のインストールおよびその後の最低必要と思われる設定変更のメモ。

インストールと設定

インストール

composer create-project codeigniter4/appstarter myproject

以後の情報は CodeIgniter v4.2.0 を前提としています。

システムメッセージの翻訳をインストール

最新の開発版をインストールします。本体のバージョンに合わせたタグ付けがなされているので、同じバージョンを指定するのも良いと思いますが翻訳は基本的に最新がいいよねという判断で最新の開発版に。

composer require codeigniter4/translations:dev-develop

コミット

オリジナルを変えてからコミットするとややこしくなるので、一旦この時点で初期ソースコードとしてコミットしておきます。

git init
git commit -m "Initial commit"

設定

本番環境と共通設定項目は app/Config/ フォルダで、開発環境固有の設定項目は .env ファイルで設定します。

サンプルの env にもコメントで書いてありますが、変数指定に . だけでなく _ も使えます。標準では . を使っていますが Docker Compose V2 のように .env. を使うとエラーになるようなソフトウェアと組み合わせて使いたいときに _ が代わりに使えます。

URLから index.php を削除

--- a/app/Config/App.php
+++ b/app/Config/App.php
@@ -37,7 +37,7 @@
      *
      * @var string
      */
-    public $indexPage = 'index.php';
+    public $indexPage = '';
 
     /**
      * --------------------------------------------------------------------------

デフォルトの言語を日本語に

@@ -70,7 +70,7 @@
      *
      * @var string
      */
-    public $defaultLocale = 'en';
+    public $defaultLocale = 'ja';
 
     /**
      * --------------------------------------------------------------------------

サポート言語に ja を追加

@@ -97,7 +97,7 @@
      *
      * @var string[]
      */
-    public $supportedLocales = ['en'];
+    public $supportedLocales = ['en', 'ja'];
 
     /**
      * --------------------------------------------------------------------------

タイムゾーンを日本時間に

@@ -109,7 +109,7 @@
      *
      * @var string
      */
-    public $appTimezone = 'America/Chicago';
+    public $appTimezone = 'Asia/Tokyo';
 
     /**
      * --------------------------------------------------------------------------

CURLRequest はデフォルトだと歴史的な理由から同一インスタンスで複数リクエストを送信するとオプションを共有する設定になっているのでそれを無効化

--- a/app/Config/CURLRequest.php
+++ b/app/Config/CURLRequest.php
@@ -18,5 +18,5 @@
      *
      * @var bool
      */
-    public $shareOptions = true;
+    public $shareOptions = false;
 }

デフォルトだと CSRF フィルタが無効なので有効化しつつ、より安全な Session ベースの保護に切り替え

--- a/app/Config/Filters.php
+++ b/app/Config/Filters.php
@@ -34,7 +34,7 @@
     public $globals = [
         'before' => [
             // 'honeypot',
-            // 'csrf',
+            'csrf',
             // 'invalidchars',
         ],
         'after' => [
--- a/app/Config/Security.php
+++ b/app/Config/Security.php
@@ -15,7 +15,7 @@
      *
      * @var string 'cookie' or 'session'
      */
-    public $csrfProtection = 'cookie';
+    public $csrfProtection = 'session';
 
     /**
      * --------------------------------------------------------------------------

ついでにより安全にする為トークンのランダム化も有効化

@@ -26,7 +26,7 @@
      *
      * @var bool
      */
-    public $tokenRandomize = false;
+    public $tokenRandomize = true;
 
     /**
      * --------------------------------------------------------------------------

デフォルトだと無効になっているマルチフィルタ機能を有効化

--- a/app/Config/Feature.php
+++ b/app/Config/Feature.php
@@ -23,7 +23,7 @@
      *
      * @var bool
      */
-    public $multipleFilters = false;
+    public $multipleFilters = true;
 
     /**
      * Use improved new auto routing instead of the default legacy version.

自動ルーティングは問題があるということで非推奨とされていましたが v4.2.0 で改善されたとのことなので有効化

--- a/app/Config/Feature.php
+++ b/app/Config/Feature.php
@@ -28,5 +28,5 @@
     /**
      * Use improved new auto routing instead of the default legacy version.
      */
-    public bool $autoRoutesImproved = false;
+    public bool $autoRoutesImproved = true;
 }
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -25,7 +25,7 @@
 // where controller filters or CSRF protection are bypassed.
 // If you don't want to define all routes, please use the Auto Routing (Improved).
 // Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.
-//$routes->setAutoRoute(false);
+$routes->setAutoRoute(true);
 
 /*
  * --------------------------------------------------------------------

自動ルーティングは便利なんですが無効にして全てのルートを手動で定義した方が安全なはずなので、利用は計画的に

動作確認

下記のコマンドで PHP のビルドインサーバが起動します。

php spark serve

更新方法

導入時点では最新ですが、更新されたら変更内容を取り込む必要があります。
vendor/ 以下にある CodeIgniter のソースコードは composer update で更新されますが、それ以外の app/ フォルダ内にあるファイルは自動更新できません。

なのでそれらを更新してくれる Liaison Revision を使います。

composer require liaison/revision

更新コマンド

php spark revision:update
CodeIgniter v4.2.0 Command Line Tool - Server Time: 2022-06-13 21:35:27 UTC+09:00

Liaison Revision
Version: 1.1.0
Run Date: Mon, 13 June 2022, 21:35:27 UTC+09:00

Loaded configuration settings from: Liaison\Revision\Config\Revision.
+---------------------------+--------------------------------------------------------+
| Setting                   | Value                                                  |
+---------------------------+--------------------------------------------------------+
| Root Path                 | /Users/katsuhidem/work/myproject/                      |
| Write Path                | /Users/katsuhidem/work/myproject/writable/             |
| Ignored Directories Count | 0                                                      |
| Ignored Files Count       | 0                                                      |
| Allow Gitignore Entry     | Allowed                                                |
| Fall Through to Project   | Allowed                                                |
| Maximum Retries           | 10                                                     |
| Consolidator              | Liaison\Revision\Consolidation\DefaultConsolidator     |
| Upgrader                  | Liaison\Revision\Upgrade\ComposerUpgrader              |
| Pathfinder                | Liaison\Revision\Paths\DefaultPathfinder               |
| Diff Output Builder       | SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder |
| Log Handlers Count        | 2                                                      |
+---------------------------+--------------------------------------------------------+

Starting software updates...

Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Generating autoload files
32 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

Found 7 files to consolidate.
[p] Proceed.
[l] List all files to consolidate.
[c] List created files only (0).
[m] List modified files only (7).
[d] List deleted files only (0).
[a] Abort.

What shall I do? [p, l, c, m, d, a]:

p を選択して処理を進める

What shall I do? [p, l, c, m, d, a]: p

Found 7 files in conflict.
[l] List all files in conflict.
[o] Overwrite all.
[b] Create backup files then safely overwrite all.
[s] Skip all.
[r] Resolve each conflict.
[a] Abort.

What shall I do? [l, o, b, s, r, a]:

最後はGitで差分を確認するので o を選択して全ての変更を上書きする

What shall I do? [l, o, b, s, r, a]: o

Logs for this run can be found here:
/Users/katsuhidem/work/myproject/writable/revision/logs/

Terminating: Application update was successful.
Software updates finished in 3.250 minutes.

今回はすでに最新バージョンを利用しているので上で変更したファイルがオリジナルに戻るだけですが、通常は CodeIgniter のバージョンアップに伴って発生した差分と、変更内容がオリジナルのファイルに差し戻ったことにより発生する差分と二種類の差分が発生しているはずなので、アップグレードノートをチェックしつつ、Git で差分を確認して必要な差分だけを取り込む必要があります。

参考

5
2
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
5
2