2016-11-02 8 views
0

私のスリムフレームワークアプリケーションでエラーが発生しています。私は双子座がなぜ機能していないのか分かりません。 twig-viewはベンダのディレクトリにダウンロードされます。 が、これはphpSlim twg-view not working

<?php 
require __DIR__ . '/vendor/autoload.php'; 
// Settings 
$config = [ 
    'settings' => [ 
     'displayErrorDetails' => true, 
     'addContentLengthHeader' => false, 
    ], 
]; 

$app = new \Slim\App($config); 

// Get container 
$container = $app->getContainer(); 

// Register component on container 
$container['view'] = function ($container) { 
    $view = new \Slim\Views\Twig(__DIR__ . '/resources/views', [ 
     'cache' => false 
    ]); 

    // Instantiate and add Slim specific extension 

    $view->addExtension(new Slim\Views\TwigExtension(
    $container['router'], 
    $container['request']->getUri() 

    )); 

    return $view; 
}; 

// Home 
$app->get('/home','index'); 



function index($request, $response, $args) 
{ 
    return $this->view->render($response, 'home.twig'); // here is the error 
} 

$app->run(); 

私はエラーオム$あなたがincorectlyルートを宣言している。このキーワード エラーの詳細

Details 

Type: Error 
Message: Using $this when not in object context 
File: C:\xampp\htdocs\slim\api\index.php 
Line: 42 

答えて

1

これを使用することはできませんあなたが閉鎖に

を持っていないときは、ルートコールバックとして閉鎖インスタンスを使用する場合は、クロージャの状態は、コンテナのインスタンスにバインドされています。つまり、$thisキーワードを使用してClosure内のDIコンテナインスタンスにアクセスできます。

(参考:http://www.slimframework.com/docs/objects/router.html

あなたは私がビューを使用せずに応答を返したときに宣言が私のために働いたことを変数

$indexRoute = function ($request, $response, $args) 
{ 
    return $this->view->render($response, 'home.twig'); // here is the error 
} 

$app->get('/home', $indexRoute); 
0

を取得しています私のインデックスファイルである、代わりに関数を宣言するの

// This callback will process GET request to /index URL  
$app->get('/index', function($request, $response, $args) { 
    return $this->view->render($response, 'home.twig'); 
}); 

を試してみてくださいルートを登録するには、$appメソッドを呼び出す必要があります。

EDIT

また、コールバックから「分離」ルート宣言することが可能です。

// Declaring a controller class with __invoke method, so it acts as a function 
class MyController 
{ 

    public function __invoke($request, $resposne) 
    { 
     // process a request, return response 
    } 

} 

// And here's how you add it to the route 
$app->get('/index', 'MyController'); 

私はあなたがappropriate section of the documentationを読むことをお勧め:あなたはこのように、別々のクラス(MVCパターンのラコントローラ)を作成することができます。それは簡単ではない。

+0

に閉鎖を割り当てるときは、それを分離することができます。ルートと呼び出し可能を分離することは可能ですか? –

+0

従来のコントローラを使用することができます。私は答えを更新し、ドキュメントへのリンクを追加しました。 –