We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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: https://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



965
edited Jun '19

You could use setPrefix() of the router group

https://docs.phalcon.io/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?)



125.7k
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.phalcon.io/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.phalcon.io/3.4/en/routing#routing-to-modules