Router::parseExtensions() for only a specifc route - cakephp

Is it possible to use Router::parseExtensions() for only one route?
I need the xml extension only for my SitemapsController but for no other routes. Using Router::parseExtensions(array('xml')) also serves the unwanted /news/foo.xml which equals /news/foo (duplicate content).

If you need request something like this
http://localhost/sitemap.xml
Then add route:
Router::connect('/sitemap.xml', array('controller' => 'sitemaps', 'action' => 'index'));
Add beforeFilter() function to SitemapsController.php:
public function beforeFilter() {
$this->viewClass = 'Xml';
}
If you don't want to set extension in route rule and want more complex solution, you have to set correct action:
public function beforeFilter() {
$this->viewClass = 'Xml';
$action = reset(explode(".", $this->request->params['action']));
$this->setAction($action);
}

Related

Cakephp Routing to generate URL parameter

Simple question for Cakephp 2.0.
I want to set a routing rule such that:
www.abc.com/z/abc123
will resolve to the full URL of (including the URL parameter)
www.abc.com/bookings/bookingref/?ref=abc123
Where bookings is the Controller, and bookingref is the action.
Can someone teach me what I need to write in the routes.php?
Kevin
In routes.php:
Router::connect('/bookingref/', array('controller' => 'bookings', 'action' => 'bookingref'));
In controller:
public function bookingref(){
}
So you should have a view name after your function. i.e. bookingref.ctp
This is how I would implement your solution:
In Config/routes.php add:
Router::connect('/z/:reference',
['controller' => 'bookings', 'action' => 'bookingref'],
[
'pass' => ['reference'],// Passed to corresponding function argument (order matters if 2 or more)
'reference' => '[a-z0-9]+'// RegExp validation if you need it
]
);
In your BookingsController use:
public function bookingref($reference = null)
{
...
}
Unfortunately, Router::redirect() cannot redirect to string based URLs that include variables. The controller based approach Progredi mentioned is your best bet.

How to tell cakephp to go to someurl.com/action/var1/var2

Please bear with me as I am a cakephp noob. I have this app that should go to www.name.com/complexes/somecomplex/unitnumber. I can correctly get it to advance to www.name.com/complexes/somecomplex, but I don't know how to get the full path to my unit number.
Here is my controller:
class ComplexesController extends AppController {
public $name='Complexes';
public $uses=array('User', 'Complex', 'Unit');
public $layout='pagelayout';
public function view() {
$this->set('complex', strtoupper($this->params['id']));
$c=$this->Complex->find('first', array('conditions'=>array('complex_name'=>$this->params['id'])));
$this->set('complex_data', $c);
}
}
and here is my route
Router::connect('/complexes/:id', array('controller' => 'complexes', 'action' => 'view'));
Where do I write the action for calling up a specific unit? Inside my 'view' action or another action called 'unit'? And how do i tell cake to route to that?
I figured it out! I had to pass an argument, called $unit in my view() function, where I set the conditions to look for the unitnumber that I had entered in the url ($unit). so, my code ended up looking like this:
public function view($unit=null) {
$this->set('complex', strtoupper($this->params['id']));
$c=$this->Complex->find('first', array('conditions'=>array('complex_name'=>$this->params['id'])));
$this->set('complex_data', $c);
$u=$this->Unit->find('first', array('conditions'=>array('unitnum'=>$unit)));
$this->set('unit', $u);
}
and in my routes file I added this line:
Router::connect('/complexes/:id/*', array('controller' => 'complexes', 'action' => 'view'));
And it worked!

CakePHP Custom Route Classes - How to Pass Arguments?

I've created a custom route class and I want to be able to pass in settings/options to the constructor so that it's configurable. Can this be done?
Documentation for Custom Route Classes:
http://book.cakephp.org/2.0/en/development/routing.html#custom-route-classes
My custom route class:
https://github.com/Signified/CakePHP-Model-Route-Class
You can probably just pass any settings/options you might have in the options of your Router::connect function.
App::import('Lib', 'ModelRoute');
Router::connect('/', array('controller' => 'pages', 'action' => 'display'),
Array('routeClass' => 'ModelRoute',
'someMoreOptions' => 'OptionValue' ));
Then you can retrieve the key someMoreOptions in your constructor
public function __construct($settings = array())
{
$this->settings = Set::merge($this->settings, $settings);
// Now you can do something with the option passed.
if(isset($this->settings['someMoreOptions'])
DoSomethingWith($this->settings['someMoreOptions']);
}

CakePHP routing with colon separator

I need to create routes that include a colon to produce URLs like http://app.com/prjct:a9b5c. Obviously it's currently simple to use a slash instead with the default routing.
$SLUG = array('slug' => '[-_A-Za-z0-9]+');
Router::connect('/prjct/:slug', array('controller' => 'projects', 'action' => 'show'), $SLUG);
But routes specifications use the colon character as a special indicator, which interferes with my naive attempt to replace the second slash above with another colon.
How do I use colons in this case for a route?
You can use named parameter as explained in CakePHP Cookbook. Write code below in your app/config/routes.php:
// Parse only the 'prjct' parameter if the current action is 'show' and the controller is 'projects'.
Router::connectNamed(array('prjct' => array('action' => 'show', 'controller' => 'projects')));
// Then set default route to controller 'projects' and action 'show
Router::connect('/', array('controller' => 'projects', 'action' => 'show'));
In your projects_controller.php :
function show(prjct = null) {
// Check if prjct match the pattern
$pattern = '[-_A-Za-z0-9]+';
if(!preg_match($pattern, prjct)){
// Redirect somewhere else
}
// Rest of your code here
}
I think this is indeed out of scope for simple routes. I see two options:
Use a custom route parsing class, as described here. There isn't a whole lot of documentation on the topic, but you can extend the existing class and play around with it to get a hang of what it's doing. Then customize it to your needs.
class MyRoute extends CakeRoute {
public function parse($url) {
debug($url); // input
$route = parent::parse($url);
debug($route); // output
return $route;
}
}
Route these URLs with a catch-all route to a controller, where the parameter will be available as a named parameter in $this->params['named']. Do what you need to do there.

Adding a prefix to every URL in CakePHP

What's the cleanest way to add a prefix to every URL in CakePHP, like a language parameter?
http://example.com/en/controller/action
http://example.com/ru/admin/controller/action
It needs to work with "real" prefixes like admin, and ideally the bare URL /controller/action could be redirected to /DEFAULT-LANGUAGE/controller/action.
It's working in a retro-fitted application for me now, but it was kind of a hack, and I need to include the language parameter by hand in most links, which is not good.
So the question is twofold:
What's the best way to structure Routes, so the language parameter is implicitly included by default without having to be specified for each newly defined Route?
Router::connect('/:controller/:action/*', ...) should implicitly include the prefix.
The parameter should be available in $this->params['lang'] or somewhere similar to be evaluated in AppController::beforeFilter().
How to get Router::url() to automatically include the prefix in the URL, if not explicitly specified?
Router::url(array('controller' => 'foo', 'action' => 'bar')) should return /en/foo/bar
Since Controller::redirect(), Form::create() or even Router::url() directly need to have the same behavior, overriding every single function is not really an option. Html::image() for instance should produce a prefix-less URL though.
The following methods seem to call Router::url.
Controller::redirect
Controller::flash
Dispatcher::__extractParams via Object::requestAction
Helper::url
JsHelper::load_
JsHelper::redirect_
View::uuid, but only for a hash generation
Out of those it seems the Controller and Helper methods would need to be overridden, I could live without the JsHelper. My idea would be to write a general function in AppController or maybe just in bootstrap.php to handle the parameter insertion. The overridden Controller and Helper methods would use this function, as would I if I wanted to manually call Router::url. Would this be sufficient?
This is essentially all the code I implemented to solve this problem in the end (at least I think that's all ;-)):
/config/bootstrap.php
define('DEFAULT_LANGUAGE', 'jpn');
if (!function_exists('router_url_language')) {
function router_url_language($url) {
if ($lang = Configure::read('Config.language')) {
if (is_array($url)) {
if (!isset($url['language'])) {
$url['language'] = $lang;
}
if ($url['language'] == DEFAULT_LANGUAGE) {
unset($url['language']);
}
} else if ($url == '/' && $lang !== DEFAULT_LANGUAGE) {
$url.= $lang;
}
}
return $url;
}
}
/config/core.php
Configure::write('Config.language', 'jpn');
/app_helper.php
class AppHelper extends Helper {
public function url($url = null, $full = false) {
return parent::url(router_url_language($url), $full);
}
}
/app_controller.php
class AppController extends Controller {
public function beforeFilter() {
if (isset($this->params['language'])) {
Configure::write('Config.language', $this->params['language']);
}
}
public function redirect($url, $status = null, $exit = true) {
parent::redirect(router_url_language($url), $status, $exit);
}
public function flash($message, $url, $pause = 1) {
parent::flash($message, router_url_language($url), $pause);
}
}
/config/routes.php
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
Router::connect('/:language/', array('controller' => 'pages', 'action' => 'display', 'home'), array('language' => '[a-z]{3}'));
Router::connect('/:language/pages/*', array('controller' => 'pages', 'action' => 'display'), array('language' => '[a-z]{3}'));
Router::connect('/:language/:controller/:action/*', array(), array('language' => '[a-z]{3}'));
This allows default URLs like /controller/action to use the default language (JPN in my case), and URLs like /eng/controller/action to use an alternative language. This logic can be changed pretty easily in the router_url_language() function.
For this to work I also need to define two routes for each route, one containing the /:language/ parameter and one without. At least I couldn't figure out how to do it another way.
rchavik from IRC suggested this link: CakePHP URL based language switching for i18n and l10n internationalization and localization
In general, it seems that overriding Helper::url might be the solution.
An easier way might be to store the chosen language in a cookie and then not have to rewrite all the URLs. You could also potentially detect the user's browser language automatically.
However, search engines would be unlikely to pickup the various languages and you'd also lose the language if someone tried to share the link.
But love the full solution you posted, very comprehensive, thanks. :-)

Resources