2017-02-01 1 views
-1

私はミドルウェアの作成についての文書hereを読んでいます。しかし、どのフォルダやファイルを作成する必要がありますか?ドキュメントにはこの情報は含まれていません。Slim Framework 3でミドルウェアを作成するにはどうすればよいですか?

srcフォルダの下に私はmiddleware.phpを持っています。私はこのようなポストの情報を取得したい例えば

$app->post('/search/{keywords}', function ($request, $response, $args) { 
    $data = $request->getParsedBody(); 
    //Here is some codes connecting db etc... 
    return json_encode($query_response); 
}); 

を私はroutes.phpのの下にこれを作ったが、私はこのためにクラスやミドルウェアを作成したいです。どのようにできるのか?どのフォルダまたはファイルを使用する必要がありますか。

+0

どのようにミドルウェアですか?おそらくコントローラを作ろうとしていますか? https://www.slimframework.com/docs/objects/router.html#registering-a-controller-with-the-container。あなたが望むミドルウェアフォルダと意味のあるファイルを作成することができます。 – nerdlyist

+0

私はクラスHomeControllerを作りたい。どこでHomeController.phpを作成できますか? (どのフォルダの下に、src?) – user5510975

+1

'src/Controller'が良いはずです。 – nerdlyist

答えて

1

Slim3はあなたを特定のフォルダ構造に結びつけませんが、作者を使用してPSRフォルダ構造の1つを使用していると思われます。

個人的に、それは私が(まあ、単純化されたバージョン)を使用するものです:私のインデックスファイル/www/index.phpで

include_once '../vendor/autoload.php'; 

$app = new \My\Slim\Application(include '../DI/services.php', '../config/slim-routes.php'); 
$app->run(); 

/SRC /マイ/スリム/アプリケーションで。 PHP:

class Application extends \Slim\App 
{ 
    function __construct($container, $routePath) 
    { 
     parent::__construct($container); 

     include $routePath; 
     $this->add(new ExampleMiddleWareToBeUsedGlobally()); 

    } 
} 

私はDI/services.php内のすべての依存性の注入とのconfig /スリムroutes.phpの中のすべてのルート定義を定義します。 Applicationコンストラクタ内にルートを含めるので、$ thisはインクルードファイル内のアプリケーションを参照します。

は、次にDI/services.phpにあなたは

$this->get('/', 'HomeController:showHome'); //note the use of $this here, it refers to the Application class as stated above 

、最終的にはあなたのコントローラ/ SRC /マイ/スリムのような設定/スリムroutes.phpの何かに

$container = new \Slim\Container(); 
$container['HomeController'] = function ($container) { 
    return new \My\Slim\Controller\HomeController(); 
}; 
return $container; 

のようなものを持つことができます/Controller/HomeController.php

class HomeController extends \My\Slim\Controller\AbstractController 
{ 
    function showHome(ServerRequestInterface $request, ResponseInterface $response) 
    { 
     return $response->getBody()->write('hello world'); 
    } 
} 

はまた、JSONを返すための最良の方法はであります10

関連する問題