Windowsで作る - PHPプログラミングの開発環境
このページへのアクセス 今日: 1 / 昨日: 3 総計: 5289
文書の過去の版を表示しています。
Version 4.5.0
— y2sunlight 2020-03-05
Slim に戻る
関連記事
リンク
本章は、Slimフレームワークの公開サイト( GitHub ) に従い、Slim4のインストールについて説明します。
Slimのシステム要件
実行環境
プロジェクトフォルダを作成し、そこに移動します。
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が依存する以下のコンポーネントをインストールします。
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フレームワークの実装をインストールします。
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
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
公開用のディレクトリーです。ここにSlimのフロントコントローラ( index.php )があります。また、.htaccess もここに配置します。
index.php
.htaccess
Composerが使用するライブラリーの保存ディレクトリーです。Slimの本体もここに配置されます。
以下のテストプログラム( index.php )を示します。このサンプルは、Githubのサンプルを少し変更したものです。
** /your-project/public/ **
<?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; }
TODO:
require __DIR__ . '/../vendor/autoload.php';
実際の運用では、ドキュメントルートにアプリケーションを設置することも多いですが、そうでない場合は、ルーティングの設定( 上の例では get() )をフルパスで記述する必要があります。これを避けるために、Slimでは setBasePath() メソッド が用意されているので、ここではこのメソッドを使用しています。
get()
setBasePath()
例えば、アプリケーションのURIが、http://localhost:8000/your-app-path/ の場合、以下のように静的にベースパスを設定することができます:
http://localhost:8000/your-app-path/
$app->setBasePath('/your-app-path');
運用と開発でベースパスが異なる場合は、設定ファイルに保存するなどの方法もありますが、自動設定するには上例のように、$_SERVER['SCRIPT_NAME'] からアプリケーションのベースパスを取得するようにします。
$_SERVER['SCRIPT_NAME']
具体的には、Slimなどのリクエストルーターを使っているフレームワークでは全てのリクエストをフロントコントコントローラ(通常は index.php)に集中させているので、$_SERVER['SCRIPT_NAME'] の値は、/your-app-path/index.php になります。従って、dirname() でその親パスを取得するれば、アプリケーションのベースパス(/your-app-path)を取得することができます。
/your-app-path/index.php
dirname()
/your-app-path
但し、ベースパスがドキュメントルール( '/' )の場合は、ベースパスを空文字('')にする必要があります。これはルーティングの設定( get()など )がドキュメントルートからのパスを設定しているからです。また、dirname('/index.php') は Winodws処理系において '\' を返すので、'\' を '/' に置換する必要があります。
'/'
''
dirname('/index.php')
'\'
プロジェクトフォルダに移動します。
まず、ドキュメントルートをプロジェクトフォルダ下のpublicにしてPHPビルドインサーバを起動します。
php -S localhost:8000 -t public
以下にURLにアクセスして下さい。
http://localhost:8000/
画面上に 'Try /hello/world' の文字が表示されたらOKです。
'Try /hello/world'
PHPビルドインサーバは、URIリクエストのファイルが見つからない場合、index.php または index.html を返します。どちらも存在しない場合は、親ディレクトリをドキュメントルートに達するまで探し続けます。
次に、ドキュメントルートをプロジェクトフォルダにしてPHPビルドインサーバを起動してみます。
php -S localhost:8000
http://localhost:8000/public/
SlimをApache環境下で実行するには、.htaccess で、アプリケーションの全てのリクエストが index.php に集中するように rewrite を設定します。
rewrite
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [QSA,L]
この設定では、ApacheのRewriteEngineを有効にして、publicフォルダ下に実在しないファイル及びフォルダに対する全てのリクエストをindex.phpに転送します。詳しくはApacheのマニュアルを参照して下さい。