Home » Php » Slim Framework – splitting code into multiple files other than index.php

Slim Framework – splitting code into multiple files other than index.php

Posted by: admin July 12, 2020 Leave a comment

Questions:

On the documentation for Slim Framework, it says

In this example application, all the routes are in index.php but in
practice this can make for a rather long and unwieldy file! It’s fine
to refactor your application to put routes into a different file or
files, or just register a set of routes with callbacks that are
actually declared elsewhere.

It doesn’t say how to actually do this though. My only thought is that you could split code into multiple PHP files and then use include or require in index.php to reference these.

I’m also not sure what it means by “register a set of routes with callbacks that are actually declared elsewhere”

Does anyone have any thoughts on this, since the application I’m wanting to build might have quite a few routes?

How to&Answers:

There’re some thoughts on it in Slim documentation

Instead of require‘s you can use composer autoloading


“register a set of routes with callbacks that are actually declared elsewhere”

From docs:

Each routing method described above accepts a callback routine as its final argument. This argument can be any PHP callable…

So you can do:

$routeHandler = function ($request, $response) { echo 'My very cool handler'; };
$app->get('/my-very-cool-path', $routeHandler);

But usually people use classes instead of functions:
http://www.slimframework.com/docs/objects/router.html#container-resolution

I think you almost get the basic idea right. I recommend reading chapter on routing a couple of times. It covers everything pretty good.

Happy coding and let me know if you need any other help!

Answer:

Being a micro-framework, Slim does not enforce any specific method. You can either find a ready-to-use structure (Slim Skeleton Application comes to my mind) or write your own; unlike other frameworks, Slim does not try to protect you from PHP.

Route definitions can be something as simple as an array of strings:

<?php // routes.php
return [
    '/'        => ['Foo\Home',    'index'],
    '/about'   => ['Foo\Home',    'about'],
    '/contact' => ['Foo\Contact', 'form' ],
];

… which you then load and process in your index.php entry point:

$routes = require('/path/to/routes.php');
foreach ($routes as list($path, $handler)) {
    $app->get($route, $handler);
}

And you can leverage the existing Composer set up to auto-load your classes by adding the appropriate directories to composer.json:

{
    "require": {
        "slim/slim": "^3.3",
        "monolog/monolog": "^1.19"
    },
    "autoload": {
        "psr-4": {"Foo\": "./Foo/"}
    }
}

From here, it can get as complex as required: define routes in a YAML file, auto-load from defined classes, etc.

(Code samples are shown for illustration purposes and might not even be valid.)