dongxian7471 2019-02-16 13:51 采纳率: 100%
浏览 43
已采纳

如何使用slim Framework分离不同目录中的不同路由

I am having some issues setting up routes in my app in different directories. The app only loads one of the routes files.

File Structure

 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';
});

So with the above structure, only one on the routes file is loaded depending on the order in the file structure. Either the book routes or the customer routes and the order will return a Page not Found Error.

I don't understand.T

  • 写回答

1条回答 默认 最新

  • dongzenglin8292 2019-02-18 00:51
    关注

    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';
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题