Slim Framework - splitting code into several files other than index.php

The documentation for Slim Framework says:

In this example application, all routes are in index.php, but in practice this can lead to a rather long and cumbersome file! It's okay to reorganize your application to put routes in another file or files, or just register a set of routes with callbacks that are actually declared elsewhere.

He does not say how to do it in reality. My only thought is that you can split the code into multiple PHP files and then use include or require in index.php to reference them.

I'm also not sure what this means, "register a set of routes with callbacks that are actually declared elsewhere"

Does anyone have any thoughts about this since the application I want to build can have quite a few routes?

+5
source share
2 answers

There are some thoughts in it. Thin documentation

Instead of require you can use composer autoload


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

From docs :

Each routing method described above takes a callback procedure as the last 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 understood the basic idea. I recommend reading the routing chapter a couple of times. It covers everything pretty well.

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

+4
source

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

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

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

... which you load and process at the entry point index.php :

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

And you can use existing Composer to automatically 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/"} } } 

Here it can be as complicated as possible: define routes in the YAML file, automatically load certain classes, etc.

(Code samples are shown for illustration and may even be invalid.)

+6
source

Source: https://habr.com/ru/post/1257778/


All Articles