====== Slim4 インストール ====== Version 4.5.0 --- //[[http://www.y2sunlight.com|y2sunlight]] 2020-09-23// [[slim:top|Slim に戻る]] 関連記事 * Slim4 インストール * [[slim:4:concepts|Slim4 コンセプト]] * [[slim:4:request|Slim4 リクエスト]] * [[slim:4:response|Slim4 レスポンス]] * [[slim:4:routing|Slim4 ルーティング]] * [[slim:4:middleware|Slim4 ミドルウェア]] * [[slim:4:cookbook|Slim4 クックブック]] リンク * https://github.com/slimphp/Slim --- GitHub(Slimの公開サイト) ----- 本章は、Slimフレームワークの公開サイト( [[https://github.com/slimphp/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:top|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が依存する以下のコンポーネントをインストールします。 * [[https://github.com/nikic/FastRoute|nikic/fast-route]] --- Slimが採用しているリクエストルーター * [[https://github.com/php-fig/container|psr/container]] --- PSR11の[[https://www.php-fig.org/psr/psr-11/#3-interfaces|Interface]] * [[https://github.com/php-fig/http-factory|psr/http-factory]] --- PSR17の[[https://www.php-fig.org/psr/psr-17/#2-interfaces|Interface]] * [[https://github.com/php-fig/http-message|psr/http-message]] --- PSR7の[[https://www.php-fig.org/psr/psr-7/#3-interfaces|Interface]] * [[https://github.com/php-fig/http-server-handler|psr/http-server-handler]] --- PSR15の[[https://www.php-fig.org/psr/psr-15/#21-psrhttpserverrequesthandlerinterface|RequestHandlerInterface]] * [[https://github.com/php-fig/http-server-middleware|psr/http-server-middleware]] --- PSR15の[[https://www.php-fig.org/psr/psr-15/#22-psrhttpservermiddlewareinterface|MiddlewareInterface]] * [[https://github.com/php-fig/log|psr/log]] --- PSR3の[[https://www.php-fig.org/psr/psr-3/#3-psrlogloggerinterface|LoggerInterface]] \\ ===== PSR-7 実装のインストール ===== Slim4で使用するPSR-7インターフェースの実装をインストールします。PSR-7の実装のインストールは必須です。Slimのサイトでは、PSR-7の実装として以下のものが示されています。アプリケーションにとって最適なものを選択しインストールして下さい。 * [[https://github.com/slimphp/Slim-Psr7|Slim-Psr7]] --- Slimフレームワークの実装です。 * [[https://github.com/http-interop/http-factory-guzzle|Nyholm/psr7]] & [[https://github.com/Nyholm/psr7-server|Nyholm/psr7-server]] --- 利用可能な最も速く、最も厳密で、最も軽量な実装です。 * [[https://github.com/guzzle/psr7|Guzzle/psr7]] & [[https://github.com/http-interop/http-factory-guzzle|http-interop/http-factory-guzzle]] --- [[http://docs.guzzlephp.org/en/stable/index.html|Guzzle]]クライアントの実装です。ストリームとファイルを処理するための追加機能を備えています。 * [[https://github.com/laminas/laminas-diactoros|laminas-diactoros]] --- [[https://getlaminas.org/|Laminas]] (Zend Frameworkの後続) の実装です。 以下に各実装でのインストール方法を示します。 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 )を示します。この例題は、[[https://github.com/slimphp/Slim|Githubのサンプル]]を少し変更したものです。 {{fa>folder-open-o}} ** /your-project/public/ ** addErrorMiddleware(true, true, true); // Add BasePath $app->setBasePath(getBasePath()); // Add routes $app->get('/', function (Request $request, Response $response) use($app) { $response->getBody()->write('Try /hello/world'); 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環境下で実行するには、''.htaccess'' を ''index.php'' と同じディレクトリーに配置します。 RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [QSA,L] この設定は、ApacheのRewriteEngineを有効にして、''index.php'' が配置されているディレクトリー配下に実在しないファイル及びディレクトリーに対する全てのリクエストをindex.phpに転送します。詳しくはApacheの[[https://httpd.apache.org/docs/2.4/ja/mod/mod_rewrite.html|マニュアル]]を参照して下さい。 通常、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を変更する事もできます。 \\