I have a mobile page running on a subdomain "m.mydomain.com". This is all working fine, but I would like to remove the controller in the URL when using the subdomain.
m.mydomain.com/mobiles/tips
should become
m.mydomain.com/tips
by using the HTML-Helper.
At the moment a link looks like that:
$html->link('MyLink', array('controller' => 'mobiles', 'action'=> 'tips'));
I tried several possible solutions with the routes and also some hacks in the bootstrap but it did not work out for me.
开发者_如何学JAVAIn the CakeBakery I found this but that does not solve my issue.
Does anyone have an idea for this issue?
Gathering code from the page you mentioned:
Constraint: you cannot have a controller called tips
or foo
in this setup
In /config/routes.php
:
$subdomain = substr( env("HTTP_HOST"), 0, strpos(env("HTTP_HOST"), ".") );
if( strlen($subdomain)>0 && $subdomain != "m" ) {
Router::connect('/tips',array('controller'=>'mobiles','action'=>'tips'));
Router::connect('/foo', array('controller'=>'mobiles','action'=>'foo'));
Configure::write('Site.type', 'mobile');
}
/* The following is available via default routes '/{:controller}/{:action}'*/
// Router::connect('/mobiles/tips',
// array('controller' => 'mobiles', 'action'=>'tips'));
// Router::connect('/mobiles/foo',
// array('controller' => 'mobiles', 'action'=>'foo'));
In your Controller action:
$site_is_mobile = Configure::read('Site.type') ?: '';
Then in your view:
<?php
if ( $site_is_mobile ) {
// $html will take care of the 'm.example.com' part
$html->link('Cool Tips', '/tips');
$html->link('Hot Foo', '/foo');
} else {
// $html will just output 'www.example.com' in this case
$html->link('Cool Tips', '/mobiles/tips');
$html->link('Hot Foo', '/mobiles/foo');
}
?>
This will allow you to output the right links in your views (in a bit I'll show you how to write even less code) but the $html
helper will not be able -- by no amount of magic -- to use controller-action routes to another domain. Be aware that m.example.com
and www.example.com
are different domains as far as the $html
helper is concerned.
Now, if you want you can do the following in your controller to take some logic off your view:
<?php
$site_is_mobile = Configure::read('Site.type') ?: '';
if ( $site_is_mobile !== '' ) {
$tips_url = '/tips';
$foo_url = '/foo';
} else {
$tips_url = '/mobile/tips';
$foo_url = '/mobile/foo';
}
// make "urls" available to the View
$this->set($tips_url);
$this->set($foo_url);
?>
And in your view you don't need to worry about checking whether the site is being accessed via m.example.com/tips
or www.example.com/mobile/tips
:
<?php echo $html->link("Get some kewl tips", $tips_url); ?>
For more advanced routing in CakePHP-1.3 refer to Mark Story's article on custom Route classes
Let us know ;)
精彩评论