質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Q&A

解決済

4回答

4447閲覧

slim フレームワーク 表示されない

creative_09

総合スコア80

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

0グッド

0クリップ

投稿2019/12/29 06:19

編集2019/12/29 06:57

はじめてslimを使用しようとおもい、
slimをcomposerで作業ディレクトリにインストールし、
ビルトインサーバーで実行しています。
正常にパラメーターなどは渡せているのですが
twigを入れるとエラーがでます。
どうしたらよいのか教えて下さい

php7.3
slim4

composer require slim/slim
composer require slim/psr7

素の状態から行った変更は
public/index.php

<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; use \Slim\Factory\AppFactory; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); $app->get('/', function (Request $request, Response $response) { $response->getBody()->write("Hello Slim!!"); return $response; }); $app->run();

php -S localhost:8080 -t public public/index.php

この時点でパラメーターなども渡せており正常に表示されています
次に
composer require slim/twig-view
composer require php-di/php-di

templates/index.html

<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Index</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.css"> </head> <body class="container"> <h1 class="display-4">Index</h1> <p>Hello, Slim + Twig !!</p> </body> </html>

publicフォルダ内index.phpの中身を以下に変更

<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; use \DI\Container; use \Slim\Views\Twig; use \Slim\Views\TwigExtension; use \Slim\Views\TwigMiddleware; use \Slim\Factory\AppFactory; require __DIR__ . '/../vendor/autoload.php'; // DI Container $container = new Container(); // create App AppFactory::setContainer($container); $app = AppFactory::create(); // add TwigMiddleware $routeParser = $app->getRouteCollector()->getRouteParser(); $twig = new Twig('./templates', ['cache' => './templates/cache']); $twigMiddleware = new TwigMiddleware($twig, $container, $routeParser, '/'); $app->add($twigMiddleware); // '/' route $app->get('/', function ($request, $response) { return $this->get('view')->render($response, 'index.html'); }); $app->run();

php -S localhost:8080 -t public public/index.php

すると
( ! ) Fatal error: Uncaught TypeError: Argument 1 passed to Slim\Views\Twig::__construct() must be an instance of Twig\Loader\LoaderInterface, string given, called in D:\作業フォルダ\slim\public\index.php on line 25 and defined in D:\作業フォルダ\slim\vendor\slim\twig-view\src\Twig.php on line 104
( ! ) TypeError: Argument 1 passed to Slim\Views\Twig::__construct() must be an instance of Twig\Loader\LoaderInterface, string given, called in D:\作業フォルダ\slim\public\index.php on line 25 in D:\作業フォルダ\slim\vendor\slim\twig-view\src\Twig.php on line 104
上記のエラーが出ます

twig.phpの104行目ですが
public function __construct(LoaderInterface $loader, array $settings = [])

/** * @param LoaderInterface $loader Twig loader * @param array $settings Twig environment settings */ public function __construct(LoaderInterface $loader, array $settings = []) { $this->loader = $loader; $this->environment = new Environment($this->loader, $settings); }

のようになっています。
なぜ読み込めていないのかわかりません

以上、よろしくおねがいします

追記
TwigMiddleware.phpの中身です

<?php /** * Slim Framework (http://slimframework.com) * * @license https://github.com/slimphp/Twig-View/blob/master/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Views; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\App; use Slim\Interfaces\RouteParserInterface; class TwigMiddleware implements MiddlewareInterface { /** * @var Twig */ protected $twig; /** * @var RouteParserInterface */ protected $routeParser; /** * @var string */ protected $basePath; /** * @var string|null */ protected $attributeName; /** * @param App $app * @param string $containerKey * * @return TwigMiddleware */ public static function createFromContainer(App $app, string $containerKey = 'view'): self { $container = $app->getContainer(); if ($container === null) { throw new RuntimeException('The app does not have a container.'); } if (!$container->has($containerKey)) { throw new RuntimeException( "The specified container key does not exist: $containerKey" ); } $twig = $container->get($containerKey); if (!($twig instanceof Twig)) { throw new RuntimeException( "Twig instance could not be resolved via container key: $containerKey" ); } return new self( $twig, $app->getRouteCollector()->getRouteParser(), $app->getBasePath() ); } /** * @param App $app * @param Twig $twig * @param string $attributeName * * @return TwigMiddleware */ public static function create(App $app, Twig $twig, string $attributeName = 'view'): self { return new self( $twig, $app->getRouteCollector()->getRouteParser(), $app->getBasePath(), $attributeName ); } /** * @param Twig $twig * @param RouteParserInterface $routeParser * @param string $basePath * @param string|null $attributeName */ public function __construct( Twig $twig, RouteParserInterface $routeParser, string $basePath = '', ?string $attributeName = null ) { $this->twig = $twig; $this->routeParser = $routeParser; $this->basePath = $basePath; $this->attributeName = $attributeName; } /** * {@inheritdoc} */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $runtimeLoader = new TwigRuntimeLoader($this->routeParser, $request->getUri(), $this->basePath); $this->twig->addRuntimeLoader($runtimeLoader); $extension = new TwigExtension(); $this->twig->addExtension($extension); if ($this->attributeName !== null) { $request = $request->withAttribute($this->attributeName, $this->twig); } return $handler->handle($request); } }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答4

0

「Slim、TWI」に関係するドキュメントを追加。

以下が、パソコン環境です。

PHP   7.3.12
Slim/Slim  4.4
Slim/psr7  1.0
PHP-di/PHP-di 6.0
Slim/twig-view 3.0

さらに、関係するドキュメントを記述しています。


(1)本に書かれたままで、「http://localhost:8080/」を実行した結果

Fatal error: Uncaught TypeError: Argument 1 passed to Slim\Views\Twig::__construct() must be an instance of Twig\Loader\LoaderInterface, string given, called in C:\Users\xxxx\Desktop\my_slim_app\app\middleware.php on line 19 called in C:\Users\xxxx\Desktop\my_slim_app\app\middleware.php on line 19 and defined in C:\Users\xxxx\Desktop\my_slim_app\vendor\slim\twig-view\src\Twig.php:104 Stack trace: #0 C:\Users\xxxx\Desktop\my_slim_app\app\middleware.php(19): Slim\Views\Twig->__construct('../templates', Array) #1 C:\Users\xxxx\Desktop\my_slim_app\public\index.php(44): {closure}(Object(Slim\App)) #2 {main} thrown in C:\Users\xxxx\Desktop\my_slim_app\vendor\slim\twig-view\src\Twig.php on line 104

(2)そのため、(4)と(5)の修正をして、「http://localhost:8080/」を実行した結果

Hello 2 world!

(3)さらに、(4)と(5)の修正のままで、「http://localhost:8080/HANAKO」を実行した結果

{ "statusCode": 500, "error": { "type": "SERVER_ERROR", "description": "No entry or class found for 'view'" } }

(4)「my_slim_app/app/middleware.php」(修正した)の中身

<?php declare(strict_types=1); use DI\Container; use Slim\Factory\AppFactory; use Slim\Views\Twig; use Slim\Views\TwigMiddleware; return function ($app) { // Create Container $container = new Container(); // create App AppFactory::setContainer($container); $app = AppFactory::create(); // Set view in Container $container->set('view', function() { return Twig::create('../templates', ['cache' => '../templates/cache']); }); // Add Twig-View Middleware $app->add(TwigMiddleware::createFromContainer($app)); };

(5)「my_slim_app/app/routes.php」 (修正した)の中身

<?php declare(strict_types=1); use App\Application\Actions\User\ListUsersAction; use App\Application\Actions\User\ViewUserAction; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\App; use Slim\Interfaces\RouteCollectorProxyInterface as Group; return function ($app) { $app->get('/', function ($request, $response) { $response->getBody()->write('Hello 2 world!'); return $response; }); $app->get('/{name}', function ($request, $response, $args) { return $this->get('view')->render($response, 'index.html', [ 'name' => $args['name'] ]); }); };

(6)「my_slim_app/public/index.php」(本のままの無修正)の中身

<?php declare(strict_types=1); use App\Application\Handlers\HttpErrorHandler; use App\Application\Handlers\ShutdownHandler; use App\Application\ResponseEmitter\ResponseEmitter; use DI\ContainerBuilder; use Slim\Factory\AppFactory; use Slim\Factory\ServerRequestCreatorFactory; require __DIR__ . '/../vendor/autoload.php'; // Instantiate PHP-DI ContainerBuilder $containerBuilder = new ContainerBuilder(); if (false) { // Should be set to true in production $containerBuilder->enableCompilation(__DIR__ . '/../var/cache'); } // Set up settings $settings = require __DIR__ . '/../app/settings.php'; $settings($containerBuilder); // Set up dependencies $dependencies = require __DIR__ . '/../app/dependencies.php'; $dependencies($containerBuilder); // Set up repositories $repositories = require __DIR__ . '/../app/repositories.php'; $repositories($containerBuilder); // Build PHP-DI Container instance $container = $containerBuilder->build(); // Instantiate the app AppFactory::setContainer($container); $app = AppFactory::create(); $callableResolver = $app->getCallableResolver(); // Register middleware $middleware = require __DIR__ . '/../app/middleware.php'; $middleware($app); // Register routes $routes = require __DIR__ . '/../app/routes.php'; $routes($app); /** @var bool $displayErrorDetails */ $displayErrorDetails = $container->get('settings')['displayErrorDetails']; // Create Request object from globals $serverRequestCreator = ServerRequestCreatorFactory::create(); $request = $serverRequestCreator->createServerRequestFromGlobals(); // Create Error Handler $responseFactory = $app->getResponseFactory(); $errorHandler = new HttpErrorHandler($callableResolver, $responseFactory); // Create Shutdown Handler $shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails); register_shutdown_function($shutdownHandler); // Add Routing Middleware $app->addRoutingMiddleware(); // Add Error Middleware $errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false); $errorMiddleware->setDefaultErrorHandler($errorHandler); // Run App & Emit Response $response = $app->handle($request); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response);

投稿2020/01/08 15:22

編集2020/02/05 15:15
pechochan

総合スコア15

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

creative_09

2020/01/08 15:34

ありがとうございます。 こちらで動いてないのはなぜかわかりません。 色々試して入るのですが、素の状態では動いていますが、 twigを入れるとだめでした。 バージョン等はどうなっているのでしょうか? slim 4.4 twig 3.0でしょうか?
guest

0

PHPを学習中です。

実は、購入した**「Web開発のためのMySQL」**の本にて学習中です。
PHP、MySQL、フレームワークを昨年の暮れから、年末年始を利用し、
学習中でして、同じところで躓いていました。

そこで、3時間前にたまたま「TwigMiddleware」で検索して、この「質問」にぶち当たり、
「Eggpanさん」の回答をヒントに、先ほど(昨晩)1時間あまりで、動き出しました。

まっさらな状態から、フォルダー作成(my_slim)インストール(composer)して、
動き出しています。

それが、先ほどの回答ですが、何か、環境が違うとだめかもしれませんね!


その前の回答は、

**もしかして、この順も、大事! 逆は、だめかも? **

composer require php-di/php-di composer require slim/twig-view

投稿2020/01/08 14:51

編集2020/01/12 00:05
pechochan

総合スコア15

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ベストアンサー

良く分からないのですが、私も色々やっていて、やっと、解決しました。

(2020/01/08 23:12)

C:\Users\Desktop> md my_slim

composer require slim/slim composer require slim/psr7 composer require php-di/php-di composer require slim/twig-view php -S localhost:8080 -t public public/index.php

このように、インストールして、実行しました。

public/index.phpの中身

以下が、苦労した部分で、かなり修正 しました。

<?php use DI\Container; use Slim\Factory\AppFactory; use Slim\Views\Twig; use Slim\Views\TwigMiddleware; require __DIR__ . '/../vendor/autoload.php'; // Create Container $container = new Container(); // create App AppFactory::setContainer($container); $app = AppFactory::create(); // Set view in Container $container->set('view', function() { return Twig::create('./templates', ['cache' => './templates/cache']); }); // Add Twig-View Middleware $app->add(TwigMiddleware::createFromContainer($app)); // '/' route $app->get('/', function ($request, $response) { return $this->get('view')->render($response, 'index.html'); }); // Run app $app->run();

**templates/index.htmlの中身 **

<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Index</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.css"> </head> <body class="container"> <h1 class="display-4">Index</h1> <p>Hello, Slim + Twig !!</p> </body> </html>

投稿2020/01/08 14:30

編集2020/01/11 15:42
pechochan

総合スコア15

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

creative_09

2020/01/08 14:56

嬉しすぎます ありがとうございます。 早速、まっさらな状態からすべてをやり直してみました。 だめですね。。。。。動かない・・・・ composer.jsonではこうなっていました。 { "require": { "slim/slim": "^4.4", "slim/psr7": "^1.0", "php-di/php-di": "^6.0", "slim/twig-view": "^3.0" } } 今日、昼間は4.1だったのですが。。。 4.4になってますね とりあえず動いてほしいです。 中身を見ながら勉強したいのでよろしくおねがいします
Eggpan

2020/01/08 17:17

私の手元の環境だと動作しました。 もしかしてtemplates/index.html の設置パスが違うのかもしれません。 (このコードだとpublic/templates/index.htmlです) ファイルが見つからないとFatalエラーになるので落ちます。 もしエラーなどが出てないのであれば、index.phpの二行目に error_reporting(-1); ini_set('display_errors', 1); を足してみてください。 バージョンについては Slim はセマンティックバージョニングみたいなので、4.1.xから4.4.xであれば機能追加されてますが前バージョンとの互換性はあるので問題ないかと思います。
creative_09

2020/01/08 17:56

ありがとうございます。 なるほど。 今日は疲れたので明日にまた確認したいと思います。 環境をまた作らないといけないのですみません。 バージョンの話、そうだったんですね。しらなかったので参考になります
creative_09

2020/01/09 00:54

ありがとうございます。 templates/index.html の設置パス、そのとおりでした。 無事に動きましたありがとうございます。
creative_09

2020/01/09 00:55

回答頂いた内容で無事に動きました! ありがとうございます
guest

0

php

1$twig = new Twig('./templates', ['cache' => './templates/cache']);`

の部分を

php

1$twig = Twig::create('./templates', ['cache' => './templates/cache']);

としてみて動かないでしょうか。

エラー自体はコンストラクタに「Twig\Loader\LoaderInterface」クラスのインスタンスを渡す必要があるが、文字列が与えられているためにTypeErrorになっています

参考:
https://github.com/slimphp/Twig-View#user-content-usage

投稿2019/12/29 06:33

編集2019/12/29 06:37
Eggpan

総合スコア2665

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

creative_09

2019/12/29 06:54

回答ありがとうございます 今度は別のエラーとなってしまいました ( ! ) Fatal error: Uncaught TypeError: Argument 2 passed to Slim\Views\TwigMiddleware::__construct() must implement interface Slim\Interfaces\RouteParserInterface, instance of DI\Container given, called in D:\作業フォルダ\slim\public\index.php on line 26 and defined in D:\作業フォルダ\slim\vendor\slim\twig-view\src\TwigMiddleware.php on line 98 ( ! ) TypeError: Argument 2 passed to Slim\Views\TwigMiddleware::__construct() must implement interface Slim\Interfaces\RouteParserInterface, instance of DI\Container given, called in D:\作業フォルダ\slim\public\index.php on line 26 in D:\作業フォルダ\slim\vendor\slim\twig-view\src\TwigMiddleware.php on line 98 質問のところへ該当のファイルの中身を提示します ありがとううございます よろしくおねがいします
creative_09

2019/12/29 07:00

$routeParser = $app->getRouteCollector()->getRouteParser(); $twig = Twig::createg('./templates', ['cache' => './templates/cache']); $twigMiddleware = new TwigMiddleware($twig, $container, $routeParser, '/'); $app->add($twigMiddleware); 次の部分 TwigMiddlewareも TwigMiddleware::creategへ 変更したほうが良いのでしょうか?
creative_09

2019/12/29 07:02

環境はslim4ですが大丈夫でしょうか よろしくお願いたします
Eggpan

2019/12/29 08:05

回答に書いたURL(公式のGithub)にもありますが、アプリケーションにミドルウェアを追加するのであれば $app->add(TwigMiddleware::createFromContainer($app)); ではないでしょうか。 使い方が公式と違うので、何を参考にコードを書かれているのか記載したほうが良いと思います。
creative_09

2020/01/08 14:52

ありがとうございます。 あれからも色々ためしているのですが。。。。 これをみてもさっぱりわからないレベル・・・・
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問