I’m trying to build a sort of WordPress-esque CMS system to a project I’m building. I want the user to be able to create pages on the fly, and for them to appear in certain areas of the website.
I have made something similar in Symfony2, where the controller grabs a specific variable from the URL (as definded in the route.yml file, usually $id etc) and I then use the variable in the controller to display whatever content it relates to in the database.
However, I’m not used to CakePHP 2.0, and struggling to find what I need. I know it’s possible, but I don’t know the best way to achieve it. Especially as CakePHP uses a different routes file than Symfony.
How would I grab a variable from the URL and pass it for use inside a controller?
Short answer: it depends.
If you’re looking to pass parameters to a function, you don’t need to mess with routes at all; every non-named URL path segment is processed in order and handed to the action as method parameters (so
/controller/action/1234passes “1234” as the first parameter to theactionmethod in thecontrollercontroller class).Named parameters allow you to pass parameters anywhere in the URL string, and to make them optional. The form is just key:value and they’re accessed via
$this->params['named']in the controller.The last option is prefix routing. The best place to get to speed on that is naturally the CakePHP Cookbook, but the general gist is that in a route definition, you can name a path component in the URL by prefixing it with a colon, identically to how the default routes show
:controller,:pluginand:action. You can define any name you like, even optionally applying regex pattern requirements and then access it through$this->params['variablename']in the controller.