初心者用CakePHPでブログサイト①MAMPでインストールして環境構築

初心者用CakePHPでブログサイト①MAMPでインストールして環境構築

223 回閲覧されました

みなさんこんにちは、joinioです。

MAMPでCakePHPを使ってブログサイトを作ったのですが忘れない為にメモを残します。

この記事を書いているのが2024年1月ですが記事を見た時期によってはGitのコマンドやコードがバージョンに対応できなくなっているかもしれないのでご了承下さい。

私のスキル

Laravelで1年2ヶ月位個人的にアプリを作って勉強しています。

LaravelとCakePHPはPHPのフレームワークなので近い部分がありますがLaravelとコードの書き方が同じ所は解説していません。

今回の環境構築に関しては知った情報をそのまま記述している箇所があります。

だからPHPのフレームワークを全く使ったことがない人がこの記事を読むと調べないといけない部分が色々とあるはずです。

今回の解説内容

MAMPにCakePHPの4.1をインストールしてデータベースにアクセスできるようにする所までを解説しています。

htdocsの下の階層にフォルダの作成

MAMPを起動してhtdocsの下の階層にフォルダ(cakephpとします)を作成します。

phpのバージョン・composerをインストールしているかの確認

CakePHPの公式サイトに4系のPHPのバージョンの指定があるので「php -v」で自分のパソコンのPHPのバージョンを表示して満たしているかを確認します。

また「composer -v」でcomposerをインストールしているかを確認します。

CakePHPのインストール

ターミナルでcakephpまで移動して下記のコマンドを入力します、「CakeBlog1」はプロジェクト名です。

composer create-project --prefer-dist cakephp/app:4.1 CakeBlog1

インストールしている途中で下記の3つで選択をしないといけないので全て「y」にします。

Do you trust "cakephp/plugin-installer" to execute code and wish to enable it now? (writes "allow-plugins" to composer.json) [y,n,d,?]
Do you trust "dealerdirect/phpcodesniffer-composer-installer" to execute code and wish to enable it now? (writes "allow-plugins" to composer.json) [y,n,d,?]
Set Folder Permissions ? (Default to Y) [Y,n]?

最初の修正

トップページ(私の場合はhttp://localhost:8888/cakephp/CakeBlog1/)にアクセスすると下記の赤枠のエラーが表示されます。

エラーを取りますが記事にしているのでそれを読んで下さい。

データベースにアクセスできるようにする

トップページで下にスクロールするとデータベースへの接続がない状態になっています。

今回はSqliteを使います。

.envの修正

「CakePHPのプロジェクト > config > .env.example」の「.env.example」を「.env」に変更して中身の修正をします。

#!/usr/bin/env bash
# Used as a default to seed config/.env which
# enables you to use environment variables to configure
# the aspects of your application that vary by
# environment.
#
# Having this file in production is considered a **SECURITY RISK** and also decreases
# the boostrap performance of your application.
#
# To use this file, first copy it into `config/.env`. Also ensure the related
# code block for loading this file is uncommented in `config/boostrap.php`
#
# In development .env files are parsed by PHP
# and set into the environment. This provides a simpler
# development workflow over standard environment variables.
export APP_NAME="CakeBlog1"                //この行を修正
export DEBUG="true"
export APP_ENCODING="UTF-8"
export APP_DEFAULT_LOCALE="ja_JP"          //この行を修正
export APP_DEFAULT_TIMEZONE="Asia/Tokyo"   //この行を修正
export SECURITY_SALT="adfdffef"            //「」の中に適当に文字列を入れる

# Uncomment these to define cache configuration via environment variables.
#export CACHE_DURATION="+2 minutes"
#export CACHE_DEFAULT_URL="file://tmp/cache/?prefix=${APP_NAME}_default&duration=${CACHE_DURATION}"
#export CACHE_CAKECORE_URL="file://tmp/cache/persistent?prefix=${APP_NAME}_cake_core&serialize=true&duration=${CACHE_DURATION}"
#export CACHE_CAKEMODEL_URL="file://tmp/cache/models?prefix=${APP_NAME}_cake_model&serialize=true&duration=${CACHE_DURATION}"

# Uncomment these to define email transport configuration via environment variables.
#export EMAIL_TRANSPORT_DEFAULT_URL=""

# Uncomment these to define database configuration via environment variables.
#export DATABASE_URL="mysql://my_app:secret@localhost/${APP_NAME}?encoding=utf8&timezone=UTC&cacheMetadata=true&quoteIdentifiers=false&persistent=false"
#export DATABASE_TEST_URL="mysql://my_app:secret@localhost/test_${APP_NAME}?encoding=utf8&timezone=UTC&cacheMetadata=true&quoteIdentifiers=false&persistent=false"

# Uncomment these to define logging configuration via environment variables.
#export LOG_DEBUG_URL="file://logs/?levels[]=notice&levels[]=info&levels[]=debug&file=debug"
#export LOG_ERROR_URL="file://logs/?levels[]=warning&levels[]=error&levels[]=critical&levels[]=alert&levels[]=emergency&file=error"

bootstrap.phpの修正

「CakePHPのプロジェクト > config > bootstrap.php」を修正します。

<?php
declare(strict_types=1);

/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         0.10.8
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */

/*
 * Configure paths required to find CakePHP + general filepath constants
 */
require __DIR__ . '/paths.php';

/*
 * Bootstrap CakePHP.
 *
 * Does the various bits of setup that CakePHP needs to do.
 * This includes:
 *
 * - Registering the CakePHP autoloader.
 * - Setting the default application paths.
 */
require CORE_PATH . 'config' . DS . 'bootstrap.php';

use Cake\Cache\Cache;
use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;
use Cake\Datasource\ConnectionManager;
use Cake\Error\ConsoleErrorHandler;
use Cake\Error\ErrorHandler;
use Cake\Http\ServerRequest;
use Cake\Log\Log;
use Cake\Mailer\Mailer;
use Cake\Mailer\TransportFactory;
use Cake\Routing\Router;
use Cake\Utility\Security;
use Cake\Error\ErrorTrap;
use Cake\Error\ExceptionTrap;

/*
 * See https://github.com/josegonzalez/php-dotenv for API details.
 *
 * Uncomment block of code below if you want to use `.env` file during development.
 * You should copy `config/.env.example` to `config/.env` and set/modify the
 * variables as required.
 *
 * The purpose of the .env file is to emulate the presence of the environment
 * variables like they would be present in production.
 *
 * If you use .env files, be careful to not commit them to source control to avoid
 * security risks. See https://github.com/josegonzalez/php-dotenv#general-security-information
 * for more information for recommended practices.
*/


//ここからコメントアウトを外して同じ内容に変更する
if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
    $dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
    $dotenv->parse()
        ->putenv()
        ->toEnv()
        ->toServer();
}
//ここまでコメントアウトを外して同じ内容に変更する


/*
 * Read configuration file and inject configuration into various
 * CakePHP classes.
 *
 * By default there is only one configuration file. It is often a good
 * idea to create multiple configuration files, and separate the configuration
 * that changes from configuration that does not. This makes deployment simpler.
 */
 
 
 //以下コードの変更はないので省略

app_localの修正

「CakePHPのプロジェクト > config > app_local.php」を修正します。

<?php
use Cake\Database\Driver\Sqlite;        //この行を追加

/*
 * Local configuration file to provide any overrides to your app.php configuration.
 * Copy and save this file as app_local.php and make changes as required.
 * Note: It is not recommended to commit files with credentials such as app_local.php
 * into source code version control.
 */
return [
    /*
     * Debug Level:
     *
     * Production Mode:
     * false: No error messages, errors, or warnings shown.
     *
     * Development Mode:
     * true: Errors and warnings shown.
     */
    'debug' => filter_var(env('DEBUG', true), FILTER_VALIDATE_BOOLEAN),

    /*
     * Security and encryption configuration
     *
     * - salt - A random string used in security hashing methods.
     *   The salt value is also used as the encryption key.
     *   You should treat it as extremely sensitive data.
     */
    'Security' => [
        'salt' => env('SECURITY_SALT', 'f6bd7a113d60c323102826b1fc792f633bd8d13337726df2a6075336d21cb605'),
    ],

    /*
     * Connection information used by the ORM to connect
     * to your application's datastores.
     *
     * See app.php for more configuration options.
     */
    'Datasources' => [
        'default' => [
            'driver' => Sqlite::class,      //この行を追加
            // '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' => ROOT . DS . 'database' . DS . 'product.sqlite',      //この行を修正
            /**
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
             */
            //'schema' => 'myapp',



 //以下コードの変更はないので省略

フォルダの作成

一旦MAMPの接続を切ります。(下記の赤枠の状態にします)

そしてCakeBlog1の直下に「database」フォルダを作成します。(MAMPの接続を切らない状態でフォルダを作成すると上手く行かなかったので必ず接続を切ってからフォルダの作成をして下さい)

そしてMAMPの接続を入れます。(下記の赤枠の状態にします)

これでトップページを開くとデータベースにアクセスできているのが確認できます。

次回の解説

次回はコントローラーの使い方です。