CodeIgniter4のデータベースシーダー

この記事は CodeIgniter Advent Calendar 2020 - Qiita の13日目です。まだ、空きがありますので、興味のある方は気軽に参加してください。

公式チュートリアルの news テーブル(「MySQLでのデータベースの準備」参照)に入れるサンプルデータを、CodeIgniter4 のデータベースシーダーを使って追加できるようにしてみます。

CodeIgniter4 開発版への変更

CodeIgniter 4.0.4 には含まれていないシーダーを作成するコマンドが、最新の開発版には含まれているため、CodeIgniter4 を一時的に開発版に変更します。

(2021-02-23 追記) CodeIgniter 4.0.5以降にはシーダーを作成するコマンドが含まれています。

$ php builds development
$ composer update

詳細は、「CodeIgniter4を一時的に開発版に変更する」を参照してください。

Seeder ファイルの作成

ファイルの作成

sparkmake:seeder コマンドでファイルの雛形を作成します。ヘルプを確認します。

$ php spark help make:seeder

CodeIgniter v4.0.4 Command Line Tool - Server Time: 2020-12-13 09:22:11 UTC+09:00

使用法:
  make:seeder <name> [options]

説明:
  Creates a new seeder file.

引数:
  name  The seeder file name

オプション:
  -n       Set root namespace. Defaults to APP_NAMESPACE.
  --force  Force overwrite existing files.

それでは作成します。

$ php spark make:seeder NewsSeeder
CodeIgniter v4.0.4 Command Line Tool - Server Time: 2020-12-13 09:26:07 UTC+09:00

作成されたファイル: APPPATH/Database/Seeds/NewsSeeder.php

app/Database/Seeds/NewsSeeder.php ファイルができました。

app/Database/Seeds/NewsSeeder.php

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class NewsSeeder extends Seeder
{
    public function run()
    {
        //
    }
}

中身の記述

run() メソッドを記述します。

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class NewsSeeder extends Seeder
{
    public function run()
    {
        $data = [
            [
                'title' => 'Elvis sighted',
                'slug' => 'elvis-sighted',
                'body' => 'Elvis was sighted at the Podunk internet cafe. It looked like he was writing a CodeIgniter app.',
            ],
            [
                'title' => 'Say it isn\'t so!',
                'slug' => 'say-it-isnt-so',
                'body' => 'Scientists conclude that some programmers have a sense of humor.',
            ],
            [
                'title' => 'Caffeination, Yes!',
                'slug' => 'caffeination-yes',
                'body' => 'World\'s largest coffee shop open onsite nested coffee shop for staff only.',
            ]
        ];

        $this->db->table('news')->insertBatch($data);
    }
}

シーダーの実行

作成した NewsSeeder を実行します。

$ php spark db:seed NewsSeeder
CodeIgniter v4.0.4 Command Line Tool - Server Time: 2020-12-13 09:36:41 UTC+09:00

Seeded: App\Database\Seeds\NewsSeeder

挿入されたデータの確認

news テーブル

mysql コマンドで MySQL に接続して確認してみます。

mysql> select * from news \G
*************************** 1. row ***************************
   id: 1
title: Elvis sighted
 slug: elvis-sighted
 body: Elvis was sighted at the Podunk internet cafe. It looked like he was writing a CodeIgniter app.
*************************** 2. row ***************************
   id: 2
title: Say it isn't so!
 slug: say-it-isnt-so
 body: Scientists conclude that some programmers have a sense of humor.
*************************** 3. row ***************************
   id: 3
title: Caffeination, Yes!
 slug: caffeination-yes
 body: World's largest coffee shop open onsite nested coffee shop for staff only.
3 rows in set (0.01 sec)

挿入されています。

この記事は CodeIgniter Advent Calendar 2020 - Qiita の13日目です。まだ、空きがありますので、興味のある方は気軽に参加してください。

参考

Tags: codeigniter, codeigniter4, database

CodeIgniter4のデータベースマイグレーション

この記事は CodeIgniter Advent Calendar 2020 - Qiita の12日目です。まだ、空きがありますので、興味のある方は気軽に参加してください。

公式チュートリアルの news テーブル(「MySQLでのデータベースの準備」参照)の作成をデータベースマイグレーションでできるようにしてみます。

すでに作成済みの news テーブルは drop table してください。

Migration ファイルの作成

ファイルの作成

spark コマンドでファイルの雛形を作成します。

$ php spark migrate:create create_table_news

app/Database/Migrations/2020-12-11-103902_create_table_news.php のようなファイルができました。

app/Database/Migrations/2020-12-11-103902_create_table_news.php

<?php namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateTableNews extends Migration
{
    public function up()
    {
        //
    }

    //--------------------------------------------------------------------

    public function down()
    {
        //
    }
}

中身の記述

up()down() メソッドを記述します。

<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateTableNews extends Migration
{
    public function up()
    {
        $this->forge->addField(
            [
                'id' => [
                    'type' => 'INT',
                    'constraint' => 11,
                    'unsigned' => true,
                    'auto_increment' => true,
                ],
                'title' => [
                    'type' => 'VARCHAR',
                    'constraint' => '128',
                    'null' => false,
                ],
                'slug' => [
                    'type' => 'VARCHAR',
                    'constraint' => '128',
                    'null' => false,
                ],
                'body' => [
                    'type' => 'TEXT',
                    'null' => false,
                ],
            ]
        );
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('news');
    }

    //--------------------------------------------------------------------

    public function down()
    {
        $this->forge->dropTable('news');
    }
}

マイグレーションの実行

マイグレーションを実行します。

$ php spark migrate
CodeIgniter CLI Tool - Version 4.0.4 - Server-Time: 2020-12-11 19:53:00pm

すべての新しいマイグレーションを実行しています...
        実行中: (App) 2020-12-11-103902_App\Database\Migrations\CreateTableNews
Done

作成されたテーブルの確認

news テーブル

mysql コマンドで MySQL に接続して確認してみます。

mysql> desc news;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| title | varchar(128)     | NO   |     | NULL    |                |
| slug  | varchar(128)     | NO   |     | NULL    |                |
| body  | text             | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

良さそうですね。

migrations テーブル

CodeIgniter が migration 情報を保存する migrations テーブルも確認しておきましょう。

mysql> select * from migrations \G
*************************** 1. row ***************************
id: 1
version: 2020-12-11-103902
class: App\Database\Migrations\CreateTableNews
group: default
namespace: App
time: 1607683980
batch: 1
1 row in set (0.02 sec)

この記事は CodeIgniter Advent Calendar 2020 - Qiita の12日目です。まだ、空きがありますので、興味のある方は気軽に参加してください。

参考

Tags: codeigniter, codeigniter4, database

CodeIgniter4のユーザガイドをビルドする

この記事は CodeIgniter Advent Calendar 2020 - Qiita の11日目です。まだ、空きがありますので、興味のある方は気軽に参加してください。

macOS 10.15.7 で CodeIgniter4 のユーザガイドをビルドできるようにしてみます。

ユーザガイドは Sphinx を使って管理されています。

以下を参考にします。

CodeIgniter4 リポジトリの取得

CodeIgniter4 の開発リポジトリがない場合は、git clone してください。

$ git clone https://github.com/codeigniter4/CodeIgniter4.git
$ cd CodeIgniter4
$ composer install

必要なツールの確認

Python 3.5 以上が必要です。

$ python3 --version
Python 3.9.0
$ pip3 --version
pip 20.2.4 from /usr/local/lib/python3.9/site-packages/pip (python 3.9)

問題ありません。

インストール

以下のコマンドを実行すると必要なものがインストールされます。

$ pip3 install -r user_guide_src/requirements.txt

以下のパッケージがインストールされました。

Successfully installed Jinja2-2.11.2 MarkupSafe-1.1.1 Pygments-2.7.3 alabaster-0.7.12 babel-2.9.0 certifi-2020.12.5 chardet-3.0.4 docutils-0.16 idna-2.10 imagesize-1.2.0 packaging-20.7 pyparsing-2.4.7 pytz-2020.4 requests-2.25.0 snowballstemmer-2.0.0 sphinx-2.4.4 sphinx-rtd-theme-0.5.0 sphinxcontrib-applehelp-1.0.2 sphinxcontrib-devhelp-1.0.2 sphinxcontrib-htmlhelp-1.0.3 sphinxcontrib-jsmath-1.0.1 sphinxcontrib-phpdomain-0.7.1 sphinxcontrib-qthelp-1.0.3 sphinxcontrib-serializinghtml-1.1.4 urllib3-1.26.2

ユーザガイドのビルド

make html コマンドを実行し、ビルドしてみます。

$ cd user_guide_src
$ make html
Sphinx v2.4.4 を実行中
ビルド中 [mo]: 更新された 0 件のpoファイル
ビルド中 [html]:更新された 153 件のソースファイル
環境データを更新中[新しい設定] 153 件追加, 0 件更新, 0 件削除
ソースを読み込み中...[  0%] changelogs/index                                    ...
更新されたファイルを探しています... 見つかりませんでした
環境データを保存中... 完了
整合性をチェック中... 完了
preparing documents... 完了
出力中...[  0%] changelogs/index                                                ...
generating indices...  genindex完了
writing additional pages...  search完了
画像をコピー中... [ 12%] installation/../images/welcome.png                     ...
静的ファイルをコピー中... ... 完了
copying extra files... 完了
dumping search index in English (code: en)... 完了
dumping object inventory... 完了
ビルド 成功.

HTMLページはbuild/htmlにあります。

ビルド成功しました。

ブラウザで開いてみます。

今日の日付でビルドされています。

$ open build/html/index.html

CodeIgniter4 のユーザガイドの URL

CodeIgniter4 のユーザガイドの URL は 2つあって、リリース版(執筆時点では 4.0.4)の公式は以下です。

開発版のユーザガイドは以下になります。

この記事は CodeIgniter Advent Calendar 2020 - Qiita の11日目です。まだ、空きがありますので、興味のある方は気軽に参加してください。

参考

Tags: codeigniter, codeigniter4, sphinx