CodeIgniter 4.4.1 でMariaDB を使う

こちらで作成したコードに追加して、MariaDB を使います。
[CodeIgniter 4.4.1 の使い方](https://qiita.com/ekzemplaro/items/07befd9e241d9bac557b)

参考ページ
[Build Your First Application / News Section](https://codeigniter4.github.io/userguide/tutorial/news_section.html#)

## ライブラリーのインストール

```bash
sudo apt install php-mysqli
```

## MariaDB の準備

データベース　ci4tutorial
ユーザー　scott
パスワード　tiger123

データベースに接続できることを確認

```bash
mariadb -uscott -ptiger123 ci4tutorial
```

```text
$ mariadb -uscott -ptiger123 ci4tutorial
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 38
Server version: 10.11.2-MariaDB-1 Ubuntu 23.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [ci4tutorial]>
```

テーブルの作成

```sql
CREATE TABLE news (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    title VARCHAR(128) NOT NULL,
    slug VARCHAR(128) NOT NULL,
    body TEXT NOT NULL,
    PRIMARY KEY (id),
    UNIQUE slug (slug)
);
```

データの挿入

```sql
INSERT INTO news VALUES
(1,'Elvis sighted','elvis-sighted','Elvis was sighted at the Podunk internet cafe. It looked like he was writing a CodeIgniter app.'),
(2,'Say it isn\'t so!','say-it-isnt-so','Scientists conclude that some programmers have a sense of humor.'),
(3,'Caffeination, Yes!','caffeination-yes','World\'s largest coffee shop open onsite nested coffee shop for staff only.');
```

データが挿入されたことを確認

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

MariaDB [ci4tutorial]>
```

## MariaDB への接続情報

```text:.env
（省略）
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = ci4tutorial
database.default.username = scott
database.default.password = tiger123
database.default.DBDriver = MySQLi
# database.default.DBPrefix =
# database.default.port = 3306
（省略）
```

## Model

```php:app/Models/NewsModel.php
<?php

namespace App\Models;

use CodeIgniter\Model;

class NewsModel extends Model
{
    protected $table = 'news';

    public function getNews($slug = false)
    {
        if ($slug === false) {
            return $this->findAll();
        }

        return $this->where(['slug' => $slug])->first();
    }
}
```

## Controller

```php:app/Controllers/News.php
<?php

namespace App\Controllers;

use App\Models\NewsModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class News extends BaseController
{
    public function index()
    {
        $model = model(NewsModel::class);


        $data = [
            'news'  => $model->getNews(),
            'title' => 'News archive',
        ];

        return view('templates/header', $data)
            . view('news/index')
            . view('templates/footer');
    }

    public function show($slug = null)
    {
        $model = model(NewsModel::class);

	$data['news'] = $model->getNews($slug);

	if (empty($data['news'])) {
            throw new PageNotFoundException('Cannot find the news item: ' . $slug);
        }

        $data['title'] = $data['news']['title'];

        return view('templates/header', $data)
            . view('news/view')
            . view('templates/footer');
    }
}
```

## View

```php:app/Views/news/index.php
<h2><?= esc($title) ?></h2>

<?php if (! empty($news) && is_array($news)): ?>

    <?php foreach ($news as $news_item): ?>

        <h3><?= esc($news_item['title']) ?></h3>

        <div class="main">
            <?= esc($news_item['body']) ?>
        </div>
        <p><a href="/news/<?= esc($news_item['slug'], 'url') ?>">View article</a></p>

    <?php endforeach ?>

<?php else: ?>

    <h3>No News</h3>

    <p>Unable to find any news for you.</p>

<?php endif ?>
```

```php:app/Views/news/view.php
<h2><?= esc($news['title']) ?></h2>
<p><?= esc($news['body']) ?></p>
```

## Routing Rule

```php:app/Config/Routes.php
<?php

use CodeIgniter\Router\RouteCollection;
use App\Controllers\News;
use App\Controllers\Pages;

/**
 * @var RouteCollection $routes
 */
$routes->get('/', 'Home::index');

$routes->get('news', [News::class, 'index']);           // Add this line
$routes->get('news/(:segment)', [News::class, 'show']); // Add this line

$routes->get('pages', [Pages::class, 'index']);
$routes->get('(:segment)', [Pages::class, 'view']);
```

## サーバーを起動

```bash
php spark serve
```

ブラウザーで、
http://localhost:8080/news/
にアクセス

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/509d9add-ac19-50ec-0367-93eaebdedde8.png)

## 確認したバージョン

```text
$ php -v
PHP 8.1.12-1ubuntu4.3 (cli) (built: Aug 17 2023 17:37:48) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.12, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.12-1ubuntu4.3, Copyright (c), by Zend Technologies
```