Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

API Versioning with MVC

Hi there I have a Phalcon MVC APi and have some php class that check for API version in URL and returns the correct one My folder structure looks like this:

├───app
│   ├───api
│   └───v1
│       ├───config
│       ├───controllers
│       ├───library
│       │   ├───Http
│       │   │   ├───Client
│       │   │   │   └───Provider
│       │   │   ├───Request
│       │   │   └───Response
│       │   └───PushService
│       │       ├───ApplePush
│       │       └───Payloads
│       ├───logs
│       ├───migrations
│       ├───models
│       │   └───Db
│       ├───services
│       └───views
│           ├───index
│           └───layouts
├───cache
├───public
│   ├───css
│   ├───files
│   ├───img
│   ├───js
│   └───temp
└───vendor

but basicly what you put inside app folder you put inside api/v1 folder here and my php script then based on url finds the right api although everything (controllers) gets loaded fine, router is givimg me problems

if I acsess url like: http://test.api/v1/somecontroller/someaction router picks v1 as controller instead of picking somecontroller

so is there a way to set a prefix to tell router to start treating controllers after v1 part?, while still maintaing convinience of not neading to define every route (as controllers are picked from controllers folder automaticly)

Thanks for Anwsering and Best Regards



176
edited 7d ago

You could use setPrefix() of the router group

https://docs.phalconphp.com/latest/en/api/Phalcon_Mvc_Router_Group

Thanks but I would like to avoid defining custom routes in router if possible, would like that router does the same thing as it always had done without any manual interaction: pick controllers from controllers dir and once you create one say testController, threat action test to testController

is there any BasePrefix I could set to avoid creating a router group (or does that mean everything will work the same it did now?)



86.5k
Accepted
answer

I have modified your initial post to use proper code demarcation - edit your post to see the change I made. Posting syntax is Markdown, not short tags.

To further help with your question - you don't need to specify each route, you could specify generic paths instead of each individual route. See the second example under this heading: https://docs.phalconphp.com/3.4/en/routing#groups-of-routes

Alternatively you could turn each api version into a module. To me, this seems like the best solution because Phalcon's set up to handle modules in pretty much the exact way you want to use URLs: https://docs.phalconphp.com/3.4/en/routing#routing-to-modules