Reverse Routing Slug-Based URL in CakePHP - cakephp

(I know there's a couple of other reverse-routing-slugs questions on this site, but I'm not having much luck relating the answers to my particular issue, so I'll ask my more specific question...)
I am building a site whose URLs now need to be slug-based, i.e. what was initially news/item/1 now has to have the URL news/firstnewsitem. And so on for a number of other controllers. I can easily get these addresses to work, and maybe even not stomp on my existing utility actions, with something like:
Router::connect('/:controller/:slug',
array('action'=>'item'),
array('pass'=>array('slug'), 'slug'=>'[^(index|add|edit|view|delete)]')
);
However, the reverse routing of these new links seems to be a non-starter: Cake is still generating such links as news/item/3. It seems optimistic to hope that a slug-based URL would automagically happen, but is there any array that I can pass in my Html->link parameters that will create the :controller/:slug format I'm looking for? Or do I have to cut my losses and back away from reverse routing at this point?

There's a pretty decent plugin for handling slug-based routing here:
https://github.com/jeremyharris/slugger
If you used this, you would be able to create links something like this
$html->link("some item", array(
'controller'=>'items',
'action'=>'view',
'Item'=>$item['id']
));
and that would output a link to /items/view/slug-for-your-item

Related

templatetags and context['request']

So i'm learning Wagtail and trying to understand how to generate menus. So far i've found the bakerydemo repo helpful. One major point of confusion for me is understanding how to use the templatetags used for menus in the bakery demo. Below is the code for the get_site_root tag (django docs recommend that as of 1.11 that simple_tag will also work and so I changed it to that.)
#register.assignment_tag(takes_context=True)
def get_site_root(context):
# This returns a core.Page. The main menu needs to have
# the site.root_page
#defined else will return an object attribute error ('str' object
#has no attribute 'get_children')
return context['request'].site.root_page
No matter what I do I can't seem to get this to work. Either nothing is returned or I get various errors like the request key isn't in context or others. I looked at the Site middleware then traced that to the site model staticmethod "find_for_request" which in turn should be calling "get_site_for_hostname" in the sites.py . Anyways, I would love some guidance on what I am doing wrong or misunderstanding. Also, any help in understading the "wagtailthonic" way of generating menus from page hierarchies would be welcome.
Here is an image of the page and site tables.

ui-router and angular-translate working together

I read different SO posts and blog posts about that question but none of them answered my questions.
Here's what I have:
Angular-translate is activated to find the preferred language, store it in localstorage/cookie and use that to translate the page.
Most people are trying to do this the other way around: someone enters a URL like domain.com/en/pagename.
I do not care about the locale in the url (although it can be there, i really don't care).
Here is what I'm trying to do:
But an important thing would be to translate the title in there for SEO and user-friendly purposes. Having:
domain.com/find-a-car/
domain.com/trouver-une-voiture/
domain.com/ein-auto-finden/
or
domain.com/en/find-a-car/
domain.com/fr/trouver-une-voiture/
domain.com/de/ein-auto-finden/
Any suggestions to achieve that ? Knowing that the page title should be dynamic, coming from the locale-??.json files !

CakePHP Routing Alias, no prefix

I have a dashboard with a series of widgets. Per specification, the widgets need to be buried under a /widgets/ directory.
So I have added the following to my routes.php
Router::connect('/widget/:controller/:action/*', array());
But I seem to be running into trouble on widget/links/ and widget/links/view/1
I am new to CakePHP, but this doesn't seem all that impressive. I have yet to find anything in the Book or by search. So any help is appreciated.
Thanks.
Well...at the risk of stating the obvious...your route starts with /widget/, but you indicate that you're trying to access it via a plural URI (/widgets/). That's a problem. If that's just a typo, it would help to know what error you're seeing when you "run into trouble".
UPDATE:
Yes that was a typo. I corrected it. The error that appears for widget/links/ is: Error: WidgetController could not be found. It appears my index/default route is the main problem.
Given that information, it appears that CakePHP thinks that widget is your controller. Cake processes routes top down and finds the first one that matches. Ensure that you don't have a route above this one that looks something like /:controller/... or any other route above this one that starts with a variable.

Dealing with Alias URLs in CakePHP

I am rewriting our company website in cakephp, and need to find a way to do the following:
A user enters our site by using one
of the promotional alias URLS that
has been pregenerated for a specific
media advert ( magazine, web
promotion etc )
The URL is checked against a
database of alias URLs, and if an
alias exists, then a specific
tracking code is written into the
session.
I have considered several options, none of which seem suitable for this purpose. They are:
Putting the lookup script in the
beforeFilter() in appcontroller, so
that its included in every
controller. (Writes a session value
so it only perfoms once.)
This option only works for existing contollers, and gives the
Cake 'missing controller' error if a
URL doesn't exist.
Specific routes for each alias in
Routes.php - Works but there are
potentially hundreds of alias urls
added/removed regularly via admin
interface.
Route all site URLs to their own
actions, and having an 'everything
else' rule, for the alias URLs that
maps to my lookup script. - Messy
and I lose the built in Cake
routing.
Custom 404. - I don't want to
return 404's for these urls, as I
feel its bad practice unless they
really don't map to anything.
I really could do with a place in the application flow where I can put this lookup/tracking script, and I'm fairly new to cake so I'm stumped.
EDIT: Also, I know that a subfolder called say 'promo' would easily do this, but I have a lot of legacy URLS from our old site, that need handling too.
Note: I'm making an assumption that your promo URLs are in the form of "domain.com/advert-259" or something like that (i.e. no "domain.com/adverts/advert-259'). That would be just too simple :)
Hopefully, you can use the routing with some regex. Add this to your /config/routes.php and let me know if a different regex will help :)
$controllers = Configure::listObjects('controller');
foreach ($controllers as &$value)
{
$value = Inflector::underscore($value);
}
Router::connect('/:promo', array('controller' => 'promos', 'action' => 'process'), array('promo' => '(?!('.implode('|', $controllers).')\W+)[a-zA-Z\-_]+/?$'));
Now you can handle all your promo codes in PromosController::process().
Basically, it checks for a promo code in url, excluding those in the $controllers array (i.e. your regular routes won't be messed up).
Later on you might want to consider caching the value of Configure::listObjects() depending on the speed of your app and your requirements.
A very interesting question. I think I would use item #3. It's not really that messy -- after all, this typically is handled by the pages controller in my stuff. That's how I'd handle it - hardcode your routes to your controllers in routes.php, then have a matchall route that will work for your promo codes. This allows you to keep legacy URLs, as well as use a lot of the standard cake stuff (you probably will just have to explicitly state each of your controllers routes, not such a chore...) Additionally, it will let you do some cool stuff with 404 errors -- you can put some logic in there to try and figure out where they were trying to go, so you can superpower your 404's.

cakephp and get requests

How does cakephp handle a get request? For instance, how would it handle a request like this...
http://us.mc01g.mail.yahoo.com/mc/welcome?.gx=1&.rand=9553121_pg=showFolder&fid=Inbox&order=down&tt=1732&pSize=20&.rand=425311406&.jsrand=3
Would "mc" be the controller and "welcome" be the action?
How is the rest of the information handled?
Also note that you could use named parameters as of Cake 1.2. Named parameters are in key:value order, so the url http://somesite.com/controller/action/key1:value1/key2:value2 would give a a $this->params['named'] array( 'key1' => 'value1', 'key2' => 'value2' ) from within any controller.
If you use a CNN.com style GET request (http://www.cnn.com/2009/SHOWBIZ/books/04/27/ayn.rand.atlas.shrugged/index.html), the parameters are in order of appearance (2009, SHOWBIZ, books, etc.) in the $this->params['pass'] array, indexed starting at 0.
I strongly recommend named paramters, as you can later add features by passing get params, without having to worry about the order. I believe you can also change the named parameter separation key (by default, it's ':').
So it's a slightly different paradigm than the "traditional" GET parameters (page.php?key1=value1&key2=value2). However, you could easily add some logic in the application to automatically parse traditional parameters into an array by tying into how the application parses requests.
CakePHP uses routes to determine this. By default, the routes work as you described. The remainder after the '?' is the querystring and it can be found in $this->params['url'] in the controller, parsed into an associative array.
Since I found this while searching for it, even though it's a little old.
$this->params['url']
holds GET information.
I have tested but it does work. The page in the Cakephp book for it is this link under the 'url' section. It even gives an example very similar to the one in the original question here. This also works in CakePHP 1.3 which is what I'm running.
It doesn't really use the get in the typical since.
if it was passed that long crazy string, nothing would happen. It expects data in this format: site.com/controller/action/var1/var2/var....
Can someone clarify the correct answer? It appears to me that spoulson's and SeanDowney's statements are contradicting each other?
Would someone be able to use the newest version of CakePHP and get the following url to work:
http://www.domain.com/index.php/oauth/authorize?oauth_version=1.0&oauth_nonce=c255c8fdd41bd3096e0c3bf0172b7b5a&oauth_timestamp=1249169700&oauth_consumer_key=8a001709e6552888230f88013f23d5d004a7445d0&oauth_signature_method=HMAC-SHA1&oauth_signature=0bj5O1M67vCuvpbkXsh7CqMOzD0%3D
oauth being the controller and authorize being a method AS WELL as it being able to accept the GET request at the end?

Resources