LoginSignup
1
2

More than 3 years have passed since last update.

Slim3 Framework×slim-skeleton不使用×twigでプロジェクトを作成する(1. プロジェクト作成~各種設定)

Last updated at Posted at 2020-07-08

はじめに

今回はslim-skeletonを使用しないSlim3フレームワークとtwigを使用したプロジェクトを作成します。
Slim3フレームワークおすすめチュートリアルで紹介した、
@nunulkさんのチュートリアルDaniel Opitzさんのやりかたで再現してみるイメージです。
成果物としては@nunulkさんのチュートリアルを通してできるものと同じものができます。
人の褌で相撲を取ってる感がすごいですが、許してください。

前提

下記記事で構築した環境を前提とします。

  • Windows10にVagrantをを入れてCentOS7をインストールしよう(123456)
  • ローカルでLAMP環境を構築しよう(01234
  • CentOS7にComposerをインストールしよう

  • 私家版 Slim Framework チュートリアル (123456)
    @nunulkさんのチュートリアルを一通り。
    ここで作成したDBを使いまわします。

手順

1. 専用のユーザーを作成
2. プロジェクトディレクトリを作成・slim3インストール
3. 各種設定
4. DocumentRootを変更&表示確認
5. Twigを使ってみよう
6. Loggingしてみよう
7. Controllerを作成しよう
8. PDOを使用してデータベースに接続しよう
9. @nunulkさんのチュートリアルで作成したチケット管理システムをtwigを使って再現しよう

やってみよう

今回の記事では、手順1~3を行います。

1. 専用のユーザーを作成

PHP Slim3フレームワークのサンプルアプリを作ろう
(2-1. First Application Walkthrough Getting Set Upまで)

1. 専用のユーザーを作成の手順で専用のユーザーを作成します。

2. プロジェクトディレクトリを作成・slim3インストール

slimuserユーザーが作成されると
/home/ディレクトリ内にslimuserディレクトリが作成されます。
その中に以下のプロジェクトディレクトリを作成します。

/home/slimuser/projects/slim/SampleApplication

以下のコマンドで、slim3をインストールします。

composer require slim/slim:3.*

3. 各種設定

SampleApplicationの下に以下のようにディレクトリ・ファイルを作成します。
Creating your first Slim 3 Framework Applicationにある手順に従って設定していきます。

ディレクトリ構成
.
├── config/             Configuration files
│   └── bootstrap.php
│   └── container.php
│   └── middleware.php
│   └── routes.php
│   └── settings.php
├── public/             Web server files (DocumentRoot)
│   └── .htaccess       Apache redirect rules for the front controller
│   └── index.php       The front controller
├── templates/          Twig templates
├── src/                PHP source code (The App namespace)
├── tmp/                Temporary files (cache and logfiles)
├── vendor/             Reserved for composer(slim3インストール時に自動生成)
├── composer.json       slim3インストール時に自動生成    
└── composer.lock       slim3インストール時に自動生成
├── .htaccess           Internal redirect to the public/ directory
└── .gitignore          Git ignore rules

Front controller

Apacheのリダイレクトの設定が記述されるファイルです。以下のように記述します。

public/.htaccess
# Redirect to front controller
RewriteEngine On
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
.htaccess
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]

Bootstrap

名前からしてTwitter社が開発したのBootstrapのことかな?と思いましたがどうもそうではない様子。
config/bootstrap.phpに使用する各種設定ファイルについて記述し、
public/index.phpから呼び出しているようです。
config/bootstrap.phppublic/index.phpをそれぞれ以下のように記述します。

public/index.php
<?php

/** @var Slim\App $app */
$app = require __DIR__ . '/../config/bootstrap.php';

$app->run();
config/bootstrap.php
<?php

require_once __DIR__ . '/../vendor/autoload.php';

$app = new \Slim\App(['settings' => require __DIR__ . '/../config/settings.php']);

require __DIR__ . '/container.php';

require __DIR__ . '/middleware.php';

require __DIR__ . '/routes.php';

return $app;

Container

アプリの依存関係の設定を行うファイルです。以下のように記述します。

config/container.php
<?php

use Slim\Container;
/** @var \Slim\App $app */
$container = $app->getContainer();

// Activating routes in a subfolder
$container['environment'] = function () {
    $scriptName = $_SERVER['SCRIPT_NAME'];
    $_SERVER['SCRIPT_NAME'] = dirname(dirname($scriptName)) . '/' . basename($scriptName);
    return new Slim\Http\Environment($_SERVER);
};

Middleware

今の時点でミドルウェアはありません。

config/middleware.php
<?php

// Slim middleware

Routes

ルーティングを行うファイルです。以下のように記述します。

config/routes.php
<?php

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

$app->get('/', function(ServerRequestInterface $request, ResponseInterface $resp
onse) {
    $response->getBody()->write("It works! This is the default welcome page");

    return $response;
})->setName('root');

$app->get('/hello/{name}', function(ServerRequestInterface $request, ResponseInterface $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, $name");

    return $response;
});

Configuration

config/settings.php
<?php

$settings = [];

$settings['displayErrorDetails'] = true;
$settings['determineRouteBeforeAppMiddleware'] = true;
$settings['addContentLengthHeader'] = false;

$settings['root'] = dirname(__DIR__);
$settings['temp'] = $settings['root'] . '/tmp';
$settings['public'] = $settings['root'] . '/public';

return $settings;

Composer

slim3インストール時に自動生成されたcomposer.jsonを以下のように編集します。

composer.json(編集前)
{
    "require": {
        "slim/slim": "3.*"
    }
}
composer.json(編集後)
{
    "require": {
        "php": ">=5.6",
        "slim/slim": "3.*"
    },
    "autoload": {
      "psr-4": {
        "App\\":"src/"
      }
    },
    "autoload-dev": {
      "psr-4": {
        "App\\Test\\": "tests/"
      }
    },
    "config": {
      "sort-packages": true
    },
    "scripts": {
        "start": "php -S 192.168.33.90:8080 -t public public/index.php",
        "test": "phpunit"
    }
}

192.168.33.90部分はご自分の環境に置き換えてください。
composer.jsonを編集した後は以下のコマンドを実行しておきましょう。

composer dump-autoload

.gitignore

vendorディレクトリはgitにコミットしませんので、以下のように記述します。

.gitignore
vendor/
.idea/

動作確認

以下のコマンドを実行します。何か記述間違いがあれば、この時点で警告されます。

composer start

ブラウザで下記のURLを開きます。
It works! This is the default welcome pageと表示されればOKです。

http://192.168.33.90:8080/

ブラウザで下記のURLを開きます。
Hello, worldと表示されればOKです。

http://192.168.33.90:8080/hello/world

参考サイト

Creating your first Slim 3 Framework Application
私家版 Slim Framework チュートリアル (1) 〜 特徴と準備編
私家版 Slim Framework チュートリアル (2) 〜 ルーティングと新規作成編
私家版 Slim Framework チュートリアル (3) 〜 表示編
私家版 Slim Framework チュートリアル (4) 〜 編集と削除、ついでにパーシャルビュー編
私家版 Slim Framework チュートリアル (5) 〜 Controllerクラス編
私家版 Slim Framework チュートリアル (6) 〜 テスト編

関連ページ

Windows10にVagrantをを入れてCentOS7をインストールしよう

1. VagrantインストールからVagrantfileを設置まで
2. 仮想マシンの操作
3. WinSCP、Tera Termに秘密鍵でログイン
4. WinSCP、Tera Termにrootユーザーでパスワードログイン
5. zip/unzipをインストール
6. Vagrantにて仮想環境を配布

ローカルでLAMP環境を構築しよう

0. 事前準備
1. Apacheをインストール
2. MySQLをインストール
3. PHPをインストール
4. ファイアウォールとか停止する

Composerをインストール

CentOS7にComposerをインストールしよう

PHP Slim3フレームワークのサンプルアプリを作ろう

2-1. First Application Walkthrough Getting Set Upまで

Apache

DocumentRootを変更しよう

Slim3 Framework×slim-skeleton不使用×twigでプロジェクトを作成する

1.プロジェクト作成~各種設定
2. DocumentRoot変更~Twigを使用
3. LoggingとController
4.PDO使用
5. チケット管理システムを再現➀
6. チケット管理システムを再現➁

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