How to create catch-all module route

28 days ago

+
0
-

My module directories look like this:

<script>
app +
    - BlogModule    +
                    - presenters
                    - templates
    - DefaultModule +
                    - presenters
                    - templates
    - ContactModule +
                    - presenters
                    - templates
</script>

I would like to create a catch-all route, where a url, such as http://example.com/blog would load the BlogModule and http://example.com/contact would load the ContactModule, and the default, if no module is specified, or the url is not found, defaults to the DefaultModule.

I have tried using this:
code

<?php
final class RouterFactory
{
        use Nette\StaticClass;

        public static function createRouter(): RouteList
        {
                $router = new RouteList;
                /// $router->addRoute('<presenter>/<action>[/<id>]', 'Homepage:default');
                $router->addRoute('/blog', 'Blog:Default:default');
                $router->addRoute('/contact', 'Contact:Default:default');
                $router->addRoute('[<module>[/<presenter>[/<action>[/<id>]]]]', 'Default:Default:default');
                return $router;
        }
}
?>

The above routes work, however, the last route forwards the url to http://example.com/default/default.
Is there a way to have routes dynamically loaded, so a route is not required for all possible variations?
Is something needed in .htaccess which currently looks like this:

<script>
Require all denied
</script>

28 days ago

David Grudl
Nette Core | 6892
+
0
-

This is a little bit tricky, but I think this should work:

$router->addRoute('[<module>[/<presenter>[/<action>[/<id>]]]]', 'Default:default');

28 days ago

+
0
-

Thanks David.
This works for /blog and for /contact, however, the default (eg: http://example.com) gives this error:

Cannot load presenter 'Default', class 'App\Presenters\DefaultPresenter' was not found.

However, http://example.com/default does load the default presenter.

So, this seems to do what I need
code

<?php
final class RouterFactory
{
        use Nette\StaticClass;

        public static function createRouter(): RouteList
        {
                $router = new RouteList;
                $router->addRoute('/', 'Default:Default:default');
                $router->addRoute('[<module>[/<presenter>[/<action>[/<id>]]]]', 'Default:default');
                return $router;
        }
}
?>

But then, if a non-existent value is given, it gives a 404, rather than return to the default.. but I think this is another question, so will start another thread.

Last edited by kevin.waterson@gmail.com (2019-11-14 01:47)