如何使用Slim Framwork分隔不同目录中的不同路由

时间:2019-02-16 13:51:15

标签: php slim-3

我在应用程序的不同目录中设置路由时遇到一些问题。该应用程序仅加载路线文件之一。

文件结构

 myapp
     |_public
     |      |_vendor
     |      |_index.php
     |_src
          |_routes
                 |_books.php
                 |_customers.php

index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require './vendor/autoload.php';

$app = new \Slim\App;

// Routes
require '../src/routes/books.php';
require '../src/routes/customers.php';
$app->run();

customers.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App;


$app->get('/api/customers', function(Request $request, Response $response){
    echo 'Customers';
});

books.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App;


$app->get('/api/books', function(Request $request, Response $response){
    echo 'Books';
});

因此,采用上述结构,仅根据文件结构中的顺序加载路由文件中的一个文件。无论是书本路线还是客户路线,订单都会返回“找不到页面”错误。

我不明白。T

1 个答案:

答案 0 :(得分:0)

You are creating a new $app instance in each route file which overrides the instance in your index.php file.

Try removing the $app instances from your route files to fix the issue:

customers.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

// $app = new \Slim\App; <-- remove this line


$app->get('/api/customers', function(Request $request, Response $response){
    echo 'Customers';
});

books.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

// $app = new \Slim\App; <-- remove this line


$app->get('/api/books', function(Request $request, Response $response){
    echo 'Books';
});