CodeIgniter4のモジュール(HMVC)内の設定ファイルとヘルパーの呼び出し方

動作確認環境

  • CodeIgniter 4.1.6-dev (4.1.5)

設定ファイル

new する

これが、基本でシンプルです。モジュールにある設定ファイルを確実にロードできます。

$config = new \Acme\Blog\Config\Blog();

config() 関数

config() 関数にクラス名を指定することもできます。 config() の実体は Factories::config() です。

$config = config(\Acme\Blog\Config\Blog::class);

しかし、app/Config/Blog.php が存在するとそちらがロードされます。 バグでしょうか?いいえ、これは Factories のデフォルト(app/ が優先される)とのことです。

(2023-08-17 追記) この完全修飾クラス名を指定しても App 名前空間にあるクラスがロードされるという、わかりづらい振る舞いは、 v4.4.0 から変更される予定です。デフォルトでは指定したクラスがロードされるようになります。

短いクラス名のみでも指定できます。

$config = config('Blog');

これも、app/Config/Blog.php が存在するとそちらがロードされます。

ヘルパー

ヘルパー名(ファイル名から _helper.php を削除したもの)を指定します。

helper('blog');

app/Helpers/blog_helper.php が存在するとそちらがロードされます。

名前空間風のヘルパー名(名前空間+ヘルパー名)を指定することもできます。

helper('Acme\Blog\blog');

名前空間に Helpers を入れてもロードされました。

helper('Acme\Blog\Helpers\blog');

関連

参考

Tags: codeigniter, codeigniter4

ZipファイルからインストールしたCodeIgniter4をComposerに変更する

動作確認環境

  • CodeIgniter 4.0.4 -> 4.1.5
  • PHP 7.3.31
  • macOS 10.15.7

Zipファイルからのインストール

Zipファイルを展開します。

$ unzip framework-4.0.4.zip

ソースコードをGit管理します。

$ cd framework-4.0.4/
$ git init
$ git add .
$ git commit -m "chore: framework-4.0.4.zip"

composer.jsonの変更

appstarterの composer.json に変更します。

composer.json を以下で上書きします。

{
  "name": "codeigniter4/appstarter",
  "type": "project",
  "description": "CodeIgniter4 starter app",
  "homepage": "https://codeigniter.com",
  "license": "MIT",
  "require": {
    "php": "^7.3 || ^8.0",
    "codeigniter4/framework": "^4"
  },
  "require-dev": {
    "fakerphp/faker": "^1.9",
    "mikey179/vfsstream": "^1.6",
    "phpunit/phpunit": "^9.1"
  },
  "suggest": {
    "ext-fileinfo": "Improves mime type detection for files"
  },
  "autoload": {
    "psr-4": {
      "App\\": "app",
      "Config\\": "app/Config"
    },
    "exclude-from-classmap": [
      "**/Database/Migrations/**"
    ]
  },
  "autoload-dev": {
    "psr-4": {
      "Tests\\Support\\": "tests/_support"
    }
  },
  "scripts": {
    "test": "phpunit"
  },
  "support": {
    "forum": "http://forum.codeigniter.com/",
    "source": "https://github.com/codeigniter4/CodeIgniter4",
    "slack": "https://codeigniterchat.slack.com"
  }
}

composer updateします。

$ composer update

codeigniter4/framework (v4.1.5) がインストールされました。

tatter/patchesのインストール

フレームワーク以外のファイルの更新をサポートするツールである tatter/patches をインストールします。

$ composer require --dev tatter/patches

フレームワーク以外のファイルの更新

tatter/patchesを実行します。-c オプションでZipインストールしたCodeIgniterのバージョンを指定します。

$ vendor/bin/patch -c 4.0.4
~/tmp/framework-4.0.4 (main)$ vendor/bin/patch -c 4.0.4
git version 2.33.1
Composer version 2.1.9 2021-10-05 09:47:38
************************************
*          CONFIGURATION           *
************************************

Scripts Directory: vendor/bin
Project Directory: /Users/kenji/tmp/framework-4.0.4
Target Version:    
Current Version:   
Source Package:    codeigniter4/framework
Base Branch:       main
Selected Items:    app/ public/ env spark

************************************
*             STAGING              *
************************************

Switched to a new branch 'tatter/scratch'
./composer.json has been updated
Running composer update codeigniter4/framework
Loading composer repositories with package information
Updating dependencies
Lock file operations: 0 installs, 1 update, 0 removals
  - Downgrading codeigniter4/framework (v4.1.5 => v4.0.4)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Downgrading codeigniter4/framework (v4.1.5 => v4.0.4): Extracting archive
Generating autoload files
29 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
infection/extension-installer: No extensions found
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Upgrading codeigniter4/framework (v4.0.4 => v4.1.5): Extracting archive
Generating autoload files
29 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
infection/extension-installer: No extensions found
[tatter/scratch 5ce6011] Patch framework
 52 files changed, 4175 insertions(+), 3184 deletions(-)
 rewrite Config/App.php (99%)
 rewrite Config/Autoload.php (75%)
 rewrite Config/Boot/development.php (84%)
 rewrite Config/Boot/production.php (75%)
 rewrite Config/Boot/testing.php (83%)
 create mode 100644 Config/CURLRequest.php
 rewrite Config/Cache.php (97%)
 rewrite Config/Constants.php (60%)
 rewrite Config/ContentSecurityPolicy.php (76%)
 create mode 100644 Config/Cookie.php
 rewrite Config/Database.php (97%)
 rewrite Config/DocTypes.php (98%)
 rewrite Config/Email.php (94%)
 rewrite Config/Encryption.php (73%)
 rewrite Config/Exceptions.php (89%)
 create mode 100644 Config/Feature.php
 rewrite Config/Filters.php (91%)
 rewrite Config/Format.php (96%)
 create mode 100644 Config/Generators.php
 rewrite Config/Honeypot.php (87%)
 rewrite Config/Images.php (88%)
 rewrite Config/Kint.php (93%)
 rewrite Config/Logger.php (98%)
 rewrite Config/Migrations.php (94%)
 rewrite Config/Mimes.php (99%)
 rewrite Config/Modules.php (97%)
 rewrite Config/Pager.php (92%)
 rewrite Config/Paths.php (89%)
 create mode 100644 Config/Publisher.php
 create mode 100644 Config/Security.php
 rewrite Config/Toolbar.php (95%)
 rewrite Config/UserAgents.php (98%)
 rewrite Config/Validation.php (97%)
 rewrite Config/View.php (99%)
 rewrite Controllers/BaseController.php (63%)
 rewrite Views/errors/cli/error_exception.php (99%)
 rewrite Views/errors/html/debug.css (78%)
 rewrite Views/errors/html/debug.js (97%)
 rewrite Views/errors/html/error_404.php (72%)
Switched to a new branch 'tatter/patches'
Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Nothing to install, update or remove
Generating autoload files
29 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
************************************
*              MERGING             *
************************************

CONFLICT (file location): Config/Security.php added in 5ce6011 (Patch framework) inside a directory that was renamed in HEAD, suggesting it should perhaps be moved to app/Config/Security.php.
CONFLICT (file location): Config/Publisher.php added in 5ce6011 (Patch framework) inside a directory that was renamed in HEAD, suggesting it should perhaps be moved to app/Config/Publisher.php.
CONFLICT (file location): Config/Generators.php added in 5ce6011 (Patch framework) inside a directory that was renamed in HEAD, suggesting it should perhaps be moved to app/Config/Generators.php.
CONFLICT (file location): Config/Feature.php added in 5ce6011 (Patch framework) inside a directory that was renamed in HEAD, suggesting it should perhaps be moved to app/Config/Feature.php.
CONFLICT (file location): Config/Cookie.php added in 5ce6011 (Patch framework) inside a directory that was renamed in HEAD, suggesting it should perhaps be moved to app/Config/Cookie.php.
CONFLICT (file location): Config/CURLRequest.php added in 5ce6011 (Patch framework) inside a directory that was renamed in HEAD, suggesting it should perhaps be moved to app/Config/CURLRequest.php.
error: could not apply 5ce6011... Patch framework
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'
On branch tatter/patches
You are currently cherry-picking commit 5ce6011.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --skip" to skip this patch)
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:
    modified:   app/Common.php
    modified:   app/Config/App.php
    modified:   app/Config/Autoload.php
    modified:   app/Config/Boot/development.php
    modified:   app/Config/Boot/production.php
    modified:   app/Config/Boot/testing.php
    modified:   app/Config/Cache.php
    modified:   app/Config/Constants.php
    modified:   app/Config/ContentSecurityPolicy.php
    modified:   app/Config/Database.php
    modified:   app/Config/DocTypes.php
    modified:   app/Config/Email.php
    modified:   app/Config/Encryption.php
    modified:   app/Config/Events.php
    modified:   app/Config/Exceptions.php
    modified:   app/Config/Filters.php
    modified:   app/Config/ForeignCharacters.php
    modified:   app/Config/Format.php
    modified:   app/Config/Honeypot.php
    modified:   app/Config/Images.php
    modified:   app/Config/Kint.php
    modified:   app/Config/Logger.php
    modified:   app/Config/Migrations.php
    modified:   app/Config/Mimes.php
    modified:   app/Config/Modules.php
    modified:   app/Config/Pager.php
    modified:   app/Config/Paths.php
    modified:   app/Config/Routes.php
    modified:   app/Config/Services.php
    modified:   app/Config/Toolbar.php
    modified:   app/Config/UserAgents.php
    modified:   app/Config/Validation.php
    modified:   app/Config/View.php
    modified:   app/Controllers/BaseController.php
    modified:   app/Controllers/Home.php
    modified:   app/Views/errors/cli/error_404.php
    modified:   app/Views/errors/cli/error_exception.php
    modified:   app/Views/errors/html/debug.css
    modified:   app/Views/errors/html/debug.js
    modified:   app/Views/errors/html/error_404.php
    modified:   app/Views/errors/html/error_exception.php
    modified:   app/Views/welcome_message.php
    modified:   env
    modified:   public/.htaccess
    modified:   public/index.php
    modified:   spark

Unmerged paths:
  (use "git add <file>..." to mark resolution)
    added by them:   app/Config/CURLRequest.php
    added by them:   app/Config/Cookie.php
    added by them:   app/Config/Feature.php
    added by them:   app/Config/Generators.php
    added by them:   app/Config/Publisher.php
    added by them:   app/Config/Security.php


************************************
*            RESOLUTION            *
************************************

Conflicts detected during patch! Follow the git instructions for resolution.
Once resolution is complete your changes will be available on branch tatter/patches
and you should remove the old working branch at tatter/scratch.

~/tmp/framework-4.0.4 (tatter/patches *+|CHERRY-PICKING)$ 

コンフリクトを手動で修正します。

修正したら、cherry-pickを完了します。

$ git add -u
$ git cherry-pick --continue

全ての変更がtatter/patchesブランチにコミットされました。

$ git log --oneline --graph
* 49e8ac6 (HEAD -> tatter/patches) Patch framework
* 14353f3 (main) chore: composer require --dev tatter/patches
* da9bf12 chore: composer update
* 0d63d1a chore: update composer.json from appstarter
* a4e451b chore: framework-4.0.4.zip

systemパスの変更

不要になった system/ を削除します。

$ git rm -r system/

パスの設定を変更します。

--- a/app/Config/Paths.php
+++ b/app/Config/Paths.php
@@ -25,7 +25,7 @@ class Paths
      *
      * @var string
      */
-    public $systemDirectory = __DIR__ . '/../../system';
+    public $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';

     /**
      * ---------------------------------------------------------------

アプリケーションコードの更新

Upgrading From a Previous Version — CodeIgniter 4.1.5 documentation をよく読んで、互換性のない変更があれば、対処します。

動作の確認

ビルトインサーバを起動して、http://localhost:8080 にアクセスします。

$ php spark serve

うまく行けば、ページが正常に表示されます。

関連

Tags: codeigniter, codeigniter4, composer

koolを使いCodeIgniter4の開発環境を構築する

(最終更新:2021-12-04)

koolを使うと、DockerでCodeIgniter4の開発環境を簡単に構築できます。

動作確認環境

  • CodeIgniter 4.1.5
  • PHP 8.0.10
  • MySQL 8.0.27
  • kool 1.14.0
  • Docker Desktop 4.2.0
  • macOS 10.15.7

koolの動作には、Docker EngineとDocker Composeが必要です。 Dockerを起動した状態で以下の作業を行って下さい。

1. kool CLIのインストール

以下のコマンドを実行し、koolコマンドをインストールします。

$ curl -fsSL https://kool.dev/install | bash
Hello, we are gonna install the latest stable version of Kool!
Downloading latest binary (kool-darwin-amd64)...
Moving kool binary to /usr/local/bin/kool...
Downloading base images...
kool version 1.14.0 installed successfully.

Windowsユーザーの方は、https://github.com/kool-dev/kool/releases からインストーラーをダウンロードしてインストールしてください。

2. CodeIgniter4プロジェクトの作成

フォルダ名(ci4app)を指定してCodeIgniter4のプロジェクトを作成します。

$ kool create codeigniter ci4app

途中、PHP、データベース、キャッシュサーバを選択します。

Creating a "codeigniter4/appstarter" project at "./ci4app"
Installing codeigniter4/appstarter (v4.1.5)
  - Downloading codeigniter4/appstarter (v4.1.5)
  - Installing codeigniter4/appstarter (v4.1.5): Extracting archive
Created project in /app/ci4app
Preset codeigniter is initializing!
? Which app service do you want to use PHP 8.0
? Which database service do you want to use MySQL 8.0
? Which cache service do you want to use Redis 6.0
Preset codeigniter initialized!

4. 設定

env を変更します。

データベースへのアクセス情報などを設定します。

--- a/env
+++ b/env
@@ -15,12 +15,13 @@
 #--------------------------------------------------------------------

 # CI_ENVIRONMENT = production
+CI_ENVIRONMENT = development

 #--------------------------------------------------------------------
 # APP
 #--------------------------------------------------------------------

-# app.baseURL = ''
+app.baseURL = 'http://localhost/'
 # app.forceGlobalSecureRequests = false

 # app.sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler'
@@ -37,19 +38,23 @@
 # DATABASE
 #--------------------------------------------------------------------

-# database.default.hostname = localhost
-# database.default.database = ci4
-# database.default.username = root
-# database.default.password = root
-# database.default.DBDriver = MySQLi
-# database.default.DBPrefix =
+DB_DATABASE = ci4app
+DB_USERNAME = dbuser
+DB_PASSWORD = dbpassword

-# database.tests.hostname = localhost
-# database.tests.database = ci4
-# database.tests.username = root
-# database.tests.password = root
-# database.tests.DBDriver = MySQLi
-# database.tests.DBPrefix =
+database.default.hostname = database
+database.default.database = "${DB_DATABASE}"
+database.default.username = "${DB_USERNAME}"
+database.default.password = "${DB_PASSWORD}"
+database.default.DBDriver = MySQLi
+database.default.DBPrefix =
+
+database.tests.hostname = database
+database.tests.database = "${DB_DATABASE}_test"
+database.tests.username = "${DB_USERNAME}"
+database.tests.password = "${DB_PASSWORD}"
+database.tests.DBDriver = MySQLi
+database.tests.DBPrefix =

 #--------------------------------------------------------------------
 # CONTENT SECURITY POLICY
@@ -123,7 +128,7 @@
 # LOGGER
 #--------------------------------------------------------------------

-# logger.threshold = 4
+logger.threshold = 9

 #--------------------------------------------------------------------
 # CURLRequest

app/Config/Cache.php を変更します。

--- a/app/Config/Cache.php
+++ b/app/Config/Cache.php
@@ -153,7 +153,7 @@ class Cache extends BaseConfig
      * @var array<string, int|string|null>
      */
     public $redis = [
-        'host'     => '127.0.0.1',
+        'host'     => 'cache',
         'password' => null,
         'port'     => 6379,
         'timeout'  => 0,

その他の詳しい設定方法は、CodeIgniter 4.1のインストール方法【2021年最新版】を参照してください。

3. 初回のセットアップ

初回のみ kool run setup を実行します。

$ cd ci4app/
$ kool run setup

これは、kool.yml に設定されている setup を実行します。

env.env にコピーし、composer install を実行し、encryption.key を生成し .env に追加します。

これで、コンテナも起動されます。

Welcomeページの確認

ブラウザで http://localhost/ にアクセスします。

Welcomeページが表示されました。

コンテナの起動

次回以降のコンテナの起動は、以下のコマンドを実行します。

$ kool start

コンテナの停止

コンテナの停止は、以下のコマンドです。

$ kool stop

その他のkoolコマンド

コンテナの状態確認

$ kool status
+----------+---------+------------------------------------------------------+----------------------+
| SERVICE  | RUNNING | PORTS                                                | STATE                |
+----------+---------+------------------------------------------------------+----------------------+
| app      | Running | 0.0.0.0:80->80/tcp, :::80->80/tcp, 9000/tcp          | Up 2 hours           |
| cache    | Running | 6379/tcp                                             | Up 2 hours (healthy) |
| database | Running | 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp | Up 2 hours (healthy) |
+----------+---------+------------------------------------------------------+----------------------+
[done] Fetching services status

ログの確認

$ kool logs app
$ kool logs -f app

コンテナのシェルを起動

$ kool exec app bash

kool CLIのアップデート

koolコマンドをアップデートする場合は、以下を実行します。

$ kool self-update

コンテナの再構築

$ kool restart --rebuild

koolで構築したCodeIgniter4開発環境にphpMyAdminを追加する」へ続く。

参考

関連

Tags: codeigniter, codeigniter4, docker