Ground Sunlight

Windowsで作る - PHPプログラミングの開発環境

ユーザ用ツール

サイト用ツール


サイドバー

メインメニュー

XAMPP アレンジ

IED

WSL2

道具箱

リポジトリ編

フレームワーク編

公開ソフトウェア

メタ
リンク


このページへのアクセス
今日: 2 / 昨日: 4
総計: 3189

slim:4:install

Slim4 インストール

Version 4.5.0

y2sunlight 2020-09-23

Slim に戻る

関連記事

リンク


本章は、Slimフレームワークの公開サイト( GitHub ) に従い、Slim4のインストールについて説明します。

Slimのシステム要件

  • PHP 7.2 or newer
  • Web server with URL rewriting

実行環境

  • XAMPP 7.3.15
  • PHP 7.3.15 (VC15 X86 64bit thread safe)
  • Composer 1.10.1


Slim4本体のインストール

プロジェクトフォルダを作成し、そこに移動します。

slim4本体のインストールは Composer を使って以下のようにします。

composer require slim/slim:"4.*"
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 8 installs, 0 updates, 0 removals
  - Installing psr/log (1.1.3): Loading from cache
  - Installing psr/http-message (1.0.1): Loading from cache
  - Installing psr/http-server-handler (1.0.1): Loading from cache
  - Installing psr/http-server-middleware (1.0.1): Loading from cache
  - Installing psr/http-factory (1.0.1): Loading from cache
  - Installing psr/container (1.0.0): Loading from cache
  - Installing nikic/fast-route (v1.3.0): Loading from cache
  - Installing slim/slim (4.5.0): Loading from cache
slim/slim suggests installing slim/psr7 (Slim PSR-7 implementation. See https://www.slimframework.com/docs/v4/start/installation.html for more information.)
slim/slim suggests installing php-di/php-di (PHP-DI is the recommended container library to be used with Slim)
Writing lock file
Generating autoload files

この時、Composerは、slim4の本体とslim4が依存する以下のコンポーネントをインストールします。


PSR-7 実装のインストール

Slim4で使用するPSR-7インターフェースの実装をインストールします。PSR-7の実装のインストールは必須です。Slimのサイトでは、PSR-7の実装として以下のものが示されています。アプリケーションにとって最適なものを選択しインストールして下さい。

以下に各実装でのインストール方法を示します。

slim

composer require slim/psr7

Nyholm PSR-7 and Nyholm PSR-7 Server

composer require nyholm/psr7 nyholm/psr7-server

Guzzle PSR-7 and Guzzle HTTP Factory

composer require guzzlehttp/psr7 http-interop/http-factory-guzzle

Laminas Diactoros

composer require laminas/laminas-diactoros

ここでは、Slimフレームワークの実装をインストールします。

composer require slim/psr7
Using version ^1.2 for slim/psr7
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 3 installs, 0 updates, 0 removals
  - Installing ralouphie/getallheaders (3.0.3): Loading from cache
  - Installing fig/http-message-util (1.1.4): Loading from cache
  - Installing slim/psr7 (1.2.0): Loading from cache
Writing lock file
Generating autoload files


その他ライブラリのインストール

HTTPデコレータ

Slimフレームワークでは、Slim-Httpライブラリを使用することが推奨されています。このライブラリーをインストールするには以下のようにします。

composer require slim/http
Using version ^1.0 for slim/http
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing slim/http (1.0.0): Loading from cache
Writing lock file
Generating autoload files


プロジェクトの配置

最も簡単なSlimプロジェクトの配置は以下のようです。

your-project [プロジェクトディレクトリー]
 |
 ├── public
 └── vendor

public ディレクトリー

公開用のディレクトリーです。ここにSlimのフロントコントローラ( index.php )を配置します。また .htaccess もここに配置します。

vendor ディレクトリー

Composerが使用するライブラリーの保存ディレクトリーです。Slimの本体もここに配置されます。


テストプログラム

以下にテストプログラム( index.php )を示します。この例題は、Githubのサンプルを少し変更したものです。

/your-project/public/

index.php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
 
require __DIR__ . '/../vendor/autoload.php';
 
// Instantiate App
$app = AppFactory::create();
 
// Add error middleware
$app->addErrorMiddleware(true, true, true);
 
// Add BasePath
$app->setBasePath(getBasePath());
 
// Add routes
$app->get('/', function (Request $request, Response $response) use($app)
{
    $response->getBody()->write('<a href="' . $app->getBasePath() . '/hello/world">Try /hello/world</a>');
    return $response;
});
 
$app->get('/hello/{name}', function (Request $request, Response $response, $args)
{
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});
 
$app->run();
 
// Get Base Path
function getBasePath()
{
    $basePath = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
    if ($basePath == '/') return '';
    return $basePath;
}

オートローディング

index.php でまず最初にしなければならないことは、composerのオートローダ( autoload.php ) を require する言です。オートローダのパスはindex.phpからの相対パスで行います。

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

これを行うことだけで、Slimをはじめとする全ての composerによって管理されているライブラリーのクラスを使用できるようになります。

ベースパス

実際の運用では、ドキュメントルートにアプリケーションを設置することも多いですが、そうでない場合は、ルーティングの設定( 上の例では get() )をフルパスで記述する必要があります。これを避けるために、Slimでは setBasePath() メソッド が用意されているので、ここではこのメソッドを使用しています。

例えば、アプリケーションのURIが、http://localhost:8000/your-app-path/ の場合、以下のように静的にベースパスを設定することができます:

$app->setBasePath('/your-app-path');

運用と開発でベースパスが異なる場合は、設定ファイルに保存するなどの方法もありますが、自動設定するには上例のように、$_SERVER['SCRIPT_NAME'] からアプリケーションのベースパスを取得するようにします。

具体的には、Slimなどのリクエストルーターを使っているフレームワークでは全てのリクエストをフロントコントコントローラ(通常は index.php)に集中させているので、$_SERVER['SCRIPT_NAME'] の値は、/your-app-path/index.php になります。従って、dirname() でその親パスを取得するれば、アプリケーションのベースパス(/your-app-path)を取得することができます。

但し、ベースパスがドキュメントルール( '/' )の場合は、ベースパスを空文字('')にする必要があります。これはルーティングの設定( get()など )がドキュメントルートからのパスを設定しているからです。また、dirname('/index.php') は Winodws処理系において '\' を返すので、'\''/' に置換する必要があります。


Slimの起動

PHPビルドインサーバからの起動 

プロジェクトフォルダに移動します。

まず、ドキュメントルートをプロジェクトフォルダ下のpublicにしてPHPビルドインサーバを起動します。

php -S localhost:8000 -t public

以下にURLにアクセスして下さい。

http://localhost:8000/

画面上に 'Try /hello/world' の文字が表示されたらOKです。

PHPビルドインサーバは、URIリクエストのファイルが見つからない場合、index.php または index.html を返します。どちらも存在しない場合は、親ディレクトリをドキュメントルートに達するまで探し続けます。

次に、ドキュメントルートをプロジェクトフォルダにしてPHPビルドインサーバを起動してみます。

php -S localhost:8000

以下にURLにアクセスして下さい。

http://localhost:8000/public/

画面上に 'Try /hello/world' の文字が表示されたらOKです。


Apacheからの起動

SlimをApache環境下で実行するには、.htaccessindex.php と同じディレクトリーに配置します。

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

この設定は、ApacheのRewriteEngineを有効にして、index.php が配置されているディレクトリー配下に実在しないファイル及びディレクトリーに対する全てのリクエストをindex.phpに転送します。詳しくはApacheのマニュアルを参照して下さい。

通常、SlimプロジェクトをWebサーバーに配置する場合、ドキュメントルート( 例えば /public_html とする)の外側にプロジェクトディレクトリーを配置します。例えば、以下のように配置するとします。

 |
 ├── your-project [プロジェクトディレクトリー]
 |    |
 |    └── vendor
 |
 └── public_html [ドキュメントルート]
      |
      ├── index.php
      └── .htaccess

この場合、index.php 内のオートローディングは以下のようになります。

require __DIR__ . '/../your-project/vendor/autoload.php';

このように、index.php の配置場所(即ち、アプリケーションのURI)に応じて、オートローディング( autoload.php )の相対パスを変更する必要があります。言い換えると、オートローディングの設定を変更するだけで、ドキュメントルート以下の任意の場所に index.php を配置する事ができます。勿論、プロジェクトディレクトリーの構成を変更することなく、ApacheのAlias設定でアプリケーションのURIを変更する事もできます。


コメント

コメントを入力. Wiki文法が有効です:
 
slim/4/install.txt · 最終更新: 2020/10/07 21:19 by y2sunlight