Controllers in many sub directories

I'm working on a big project that forces me to split my controllers into multiple sub dirs.

I have this namespace and file structure as an example:

  • MyApp\Controllers\User => app/controllers/user/UserController.php
  • MyApp\Controllers\Product => app/controllers/customer/ListingController.php

And I would like to access them as:


I've looked on previous answers but I still can't get the loader and router to work together... :-/

Any ideas how should I set my loader and router?

you have to set a individual router for controllers in sub direcotires. check this example

Good luck

edited Dec '18

That's a bit of a mess because the namespace doesn't map to the directory: "Product -> /customer/". The consequence of that is nothing can be inferred or standardized because there is no logical way to know what controller is in what namespace. And what happens if you have 2 ListingController.php files in different namespaces & directories? Where does point to?

At present, it looks like you'll have to manually create a route for each url - indicating what namespace to use for the route's controller. Then in your autoloader configuration, manually map each namespace to the directory that contains that namespace's controllers.

If you want to simplify things and make your site more maintainable, I'd recommend storing controllers in a directory that directly relates to it's namespace. So:

  • MyApp\Controllers\Product => app/controller/product/ListingController.php

accessed via:


This way you can probably set up your dispatcher, router, and/or loader to dynamically load the correct controller based on the URL, rather than having to manually defined everything. The longer URL is immaterial for practically every concern. SEO doesn't care, and users generally don't manually type links in anyway.

edited Dec '18

Just use modules, this is why they even exists. They support multi controllers out of the box. Create route group for each module, mount them and that's it, nothing more to do.