Search code examples
phproutesslim

Slim Framework ^3 multiple route files


I'm playing around with creating an API using slim framework. In a tutorial I was watching on youtube he put the routes in a separate file, seemed like a great idea until I added an additional file, i.e. two separate php files with routes. Then it defaults to the last included file and never looks at the first. I have tried every possible combination to make this work, including creating a group and including the files in the group. It seems in a larger application the index.php file would get pretty ugly if this can't be organized better.

Maybe I'm missing something, but it seems pretty straightforward to me. lol

index.php

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

require '../vendor/autoload.php';
require '../src/config/db.php';

$app = new \Slim\App;

  //labor routes
 require '../src/routes/labor.php';  
 // Testing routes
 require '../src/routes/testing.php';

$app->run();

labor.php

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

$app = new \Slim\App;

// GET all customers

// Default Route
$app->get('/api/labor', function(Request $request, Response $response){
  $response->getBody()->write("Hello, This is the Celltron, Inc. API for 
internal web. Your IP address has been logged and notification sent to the 
Administrator.");

return $response;
});

testing.php

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

$app = new \Slim\App;

// GET all testing

// Default Route
$app->get('/api/testing', function(Request $request, Response $response){
 $response->getBody()->write("Hello, This is the Celltron, Inc. testing API 
for internal web. Your IP address has been logged and notification sent to 
the Administrator.");

 return $response;
});

And if this was answered in another question that missed, please feel free to spin me in that direction. But nothing I saw matched the issue I'm seeing.

Gracias Amigos


Solution

  • You are creating a new app instance in each file, you should only have one

    $app = new \Slim\App;
    

    You can then add routes to this one app instance in different files.