Managing Simple Pages in CakePHP
Creating pages dynamically with a PagesController and using a dynamic route to publish them at any URL.
Tagged with CakePHP and Web Development
Posted on 15/7/07 by Paul Herron
As well as complex functionality like blogs or product listings, websites often need simple pages. An about us or our services page, for example, might consist of only text and images.
CakePHP has two obvious ways to set up simple pages like these. The first is to drop a view file into app/views/pages. This is quick and easy, but the page won't be dynamic and the standard URLs of /pages/about and /pages/services might seem strange when, from the user's perspective, /about and /services would be more logical.
The second approach is to set up controllers and views for the pages. The above example could use an AboutController and a ServicesController, each with their own empty index() action and an index.ctp view file. The pages are now accessible at intuitve URLs - /about and /services - and page content can easily be managed in the database, rather than being hard-coded into the view files. The disadvantage of this approach is that coding would be required to add new pages.
Alternative Approach
The best aspects of the techniques mentioned above can be combined by introducing the following:
- A
Pagemodel. This will store all of the website's simple pages. - A dynamic route in
routes.php. This will recognise URL requests for stored pages and route them through to thePagesController.
The pages database table might look something like this:
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `title` TEXT, `slug` varchar(255), `content` TEXT, `created` datetime, `modified` datetime
The slug field is simply the relative URL at which the page will be accessible. For example, a slug of about will be used to set up a page at http://example.com/about and a slug of services/technical will be available at http://example.com/services/technical.
A PagesController and corresponding views should be set up. A main index() action will be used to display the stored pages. Admin actions such as admin_add() could also be used to allow editing of the pages' content. It might also be worth taking a copy of Cake's core display() action from cake/libs/controller/pages_controller.php so that static pages in app/views/pages can still be displayed.
A route is then required to send requests for stored pages to PagesController::index(). To recognise which URLs correspond to stored pages, it will be necessary to load and query the Page model. This gives us a list of slugs to add as conditions to the $params array of the route. This could be done by putting the following code in app/config/routes.php:
// Load details of stored pages. uses('model' . DS . 'model'); loadModel('Page'); $Page = new Page(); $pages = $Page->generateList(null,'slug DESC',null,null,'{n}.Page.slug'); //If the URL matches the slug of a stored page, route to PagesController::index() and set $this->params['page'] to whatever the slug is.
Note: It's important to retrieve the page slugs in descending alphabetical order, otherwise child pages will wrongly be routed to their parents. For example, if 'services' appears in the $params array before 'services/technical', a URL requesting 'services/technical' would be routed to 'services'.
The PagesController is then free to pick up $this->params['page'] and fetch the relevant page using $this->Page->findBySlug($this->params['page']).
Extending the Idea
This is a simple description of the technique; it could of course be extended in any number of ways. For example:
- The actual page content could be stored in a separate
sectionstable. Associations could then be set up to say that a pagehasManysections and a sectionbelongsToa page. This would allow any section on a page to be linked to directly, e.g./services/technical#programming. An extension of this would be outputting an 'on this page' element which lists and links to each section on the current page. - Pages could be given a
parent_id, making a hierarchical page structure possible. For example,/servicescould be displayed as being a parent of/services/technical. - Pages could be assigned positions on navigation menus. For example, a link to the
/aboutpage could be set to appear on the site's main navigation menu.
Comments
Leave a Comment
Article Tags
Show all articles, or just those tagged as:
- Apache (1)
- CakePHP (10)
- Domains (1)
- Freeware (1)
- Graphics (1)
- Life (1)
- Open Source (2)
- Servage (1)
- SMS (1)
- Software (3)
- Ubuntu (2)
- WAMP (2)
- Web Development (13)
- Windows (2)
- Work (2)
Feed
The articles RSS feed is available.
Elsewhom
-
Modern Life.
A blog about the web - development, design, search engines and statistics. Sometimes controversial, occasionally satirical and usually on the nose. -
A List Apart.
Influential webzine for web designers -
mattheaton.com.
Bluehost Blog
Matt is CEO of Bluehost, a successful web hosting provider -
graphpaper.
Art Science Business -
cakebaker.
Baking cakes with CakePHP
Enlightening CakePHP articles

kabturek wrote on 16/7/07:
Hey
I like the idea but i would do it diffrently myself:
->i would cache the actual pages array (serilize into tmp)
->read the array and search for the desired value
-> if it exist then add the route
->i would update the cached array only when there is an add/edit/delate ( a callback in the model)
greets,
matt wrote on 7/9/08:
I would love to implement this on my site but I am somewhat new to cake, could you possible give some more detail how the index portion of the pages_controller would work?
Thanks
Andy wrote on 31/12/08:
Great article. Simple language. Lots of info.
Thanks
Michelle wrote on 2/1/09:
Brief and to the point article, but its missing any details about using mail functionality. If you can include that, it will become more valuable.
Mich.
Peter wrote on 21/12/09:
Excellent tutorial! I have taken the code and adapted it to cake 1.2 incase anyone is interested.
App::import('model', 'Page');
$Page = new Page();
$pages = $Page->find('list', array('fields' => array('id', 'permalink')));
Router::connect('/:page/*', array('controller' => 'pages'), array('page' => implode($pages, '|')));
Caelii wrote on 27/8/11:
I rellay couldn't ask for more from this article.qwvxpubasr wrote on 29/8/11:
BNxntU mseatcfjnjhfoffice2010key wrote on 16/11/11:
The Microsoft office 2011 users can Office 2010 work more efficiently with the Microsoft Office 2010 simple and intuitive Download Office 2010 user interface new graphical MS Office 2010 menus and a familiar Office 2010 Key experience provide the Office 2010 Download tools you need to plan and Office 2010 Professional manage your project. And the Microsoft Office 2010 Download tabs and contextual menu buy microsoft office 2010 groupings reveal powerful features, Windows 7 making it easier to get Microsoft Windows 7 started and realize results Win 7. Simply be more productive Download Windows 7 by choosing your own menu Buy Windows 7 options, quick access Office 2007 toolbar settings and Microsoft Office 2007 setting defaults.Enhanced copy Office 2007 Download and paste makes it easy to Office 2007 Professional share information effectively MS Office 2007 with other Office 2007 Key applications while retaining buy microsoft office 2007 formatting. And the added columns Download Office 2007 dynamically by entering Microsoft Office 2007 Professional data without having to first select purchase microsoft office 2007 the data type.
http://softwarestockss.blogspot.com
http://software-stocks.com
discount north face jackets wrote on 16/12/11:
Not because the north face are not afraid of light, discount north face jackets but because the north face did not look directly at their bird gold black. The general audience does not know black gold is normal, the north face when they However, the thing is seen, so they just fly out of sight immediately turned to the side.
Cheyenne wrote on 22/12/11:
I rlelay appreciate free, succinct, reliable data like this.Bobbi wrote on 22/12/11:
Many many qualtiy points there.Sable wrote on 22/12/11:
Damn, I wish I could think of soemthing smart like that!Frankie wrote on 22/12/11:
Created the greatest aritcles, you have.Anisha wrote on 22/12/11:
Mighty useful. Make no mitaske, I appreciate it.Laquisha wrote on 22/12/11:
That's rlaley shrewd! Good to see the logic set out so well.Kylia wrote on 22/12/11:
That's relaly shrewd! Good to see the logic set out so well.Tory wrote on 22/12/11:
At last! Something clear I can unedrtsnad. Thanks!Kourtney wrote on 22/12/11:
Your answer was just what I neeedd. It's made my day!Roseanna wrote on 22/12/11:
I was seroisuly at DefCon 5 until I saw this post.Johnelle wrote on 22/12/11:
Wow! Great thiinkng! JKCapatin wrote on 22/12/11:
I never thought I would find such an everyday topic so entrhalling!Youngy wrote on 22/12/11:
So that's the case? Quite a reevlatoin that is.Kevrell wrote on 22/12/11:
There is a critical shortage of informative atricels like this.Hester wrote on 22/12/11:
I can't believe I've been going for years whitout knowing that.Trevon wrote on 22/12/11:
That's a smart way of lokiong at the world.Krisalyn wrote on 22/12/11:
Four score and seven muintes ago, I read a sweet article. Lol thanksJoni wrote on 22/12/11:
Just do me a favor and keep writing such trenchant aanlsyes, OK?Sailor wrote on 22/12/11:
I could watch Schidenlr's List and still be happy after reading this.Bardo wrote on 22/12/11:
Extremely helpful article, plasee write more.qxgqovqnx wrote on 22/12/11:
TjxhZl rvqiafprgjlvJaylin wrote on 22/12/11:
I just hope whoever writes these keeps wirting more!Wimpy wrote on 22/12/11:
These pieces really set a standard in the inudtsry.Lorrie wrote on 22/12/11:
Keep it coming, wrietrs, this is good stuff.Blessing wrote on 22/12/11:
Your's is the intelligent aprpaoch to this issue.Margaretta wrote on 22/12/11:
Your posting raelly straightened me out. Thanks!Dell wrote on 22/12/11:
The purchases I make are entlriey based on these articles.Lucinda wrote on 22/12/11:
You are so awesome for helping me solve this mstryey.dahakaao wrote on 23/12/11:
NAEBJ7 , [url=http://lggzqpoefitq.com/]lggzqpoefitq[/url], [link=http://yqbtuhsnqevf.com/]yqbtuhsnqevf[/link], http://tnrddxhnuqzu.com/Jera wrote on 24/12/11:
Check that off the list of tinghs I was confused about.Carlynda wrote on 24/12/11:
Heck of a job there, it absoleutly helps me out.Lavigne wrote on 24/12/11:
It's good to see seomone thinking it through.Deon wrote on 24/12/11:
Slam dnuikn like Shaquille O'Neal, if he wrote informative articles.Lawanda wrote on 24/12/11:
Whoever edits and publishes these artcleis really knows what they're doing.Jobeth wrote on 24/12/11:
IJWTS wow! Why can't I think of thgnis like that?Holland wrote on 24/12/11:
You've got it in one. Couldn't have put it bteetr.Katty wrote on 24/12/11:
Wow I must cfneoss you make some very trenchant points.Magdelina wrote on 24/12/11:
You're the greaestt! JMHOJohnelle wrote on 24/12/11:
Now I'm like, well duh! Truly tnhafkul for your help.Kairii wrote on 24/12/11:
I'm so glad I found my slouiton online.Adele wrote on 24/12/11:
Ah yes, nlicey put, everyone.Janesa wrote on 24/12/11:
Tip top stuff. I'll expcet more now.Kathy wrote on 24/12/11:
Thank you so much for this artcile, it saved me time!Norm wrote on 24/12/11:
You're the graestet! JMHOMarylouise wrote on 24/12/11:
This makes everything so comlpetley painless.Loradae wrote on 24/12/11:
Hey, that post leaves me feelnig foolish. Kudos to you!Jesslyn wrote on 24/12/11:
Oh yeah, faboulus stuff there you!Leatrix wrote on 24/12/11:
Creeatd the greatest articles, you have.Janais wrote on 24/12/11:
You've impressed us all with that posintg!Bobbie wrote on 24/12/11:
One or two to rebemmer, that is.Lakisha wrote on 24/12/11:
Phenomenal berakdwon of the topic, you should write for me too!Cindy wrote on 24/12/11:
I'm impressed by your wriitng. Are you a professional or just very knowledgeable?Mitchell wrote on 24/12/11:
I really wish there were more atrciles like this on the web.Travon wrote on 24/12/11:
You've got to be kidding me-it's so tanrsparently clear now!Githa wrote on 24/12/11:
Keep on witnrig and chugging away!Raynoch wrote on 24/12/11:
Thanks for writing such an easy-to-understand arctlie on this topic.Jeanne wrote on 24/12/11:
Time to face the music armed with this great inoframtion.Tess wrote on 24/12/11:
This is way btteer than a brick & mortar establishment.Jady wrote on 24/12/11:
I'm so glad I found my soliuton online.Birdie wrote on 24/12/11:
Please keep thriowng these posts up they help tons.Gump wrote on 24/12/11:
Just the type of inishgt we need to fire up the debate.Rileigh wrote on 24/12/11:
Ya learn seomtnhig new everyday. It's true I guess!Melloney wrote on 24/12/11:
I feel so much happier now I udenrsantd all this. Thanks!Keisha wrote on 24/12/11:
Good to see real expertise on dislpay. Your contribution is most welcome.Ice wrote on 24/12/11:
Life is short, and this article saved valaulbe time on this Earth.Addy wrote on 24/12/11:
We need more insihgts like this in this thread.Deacon wrote on 24/12/11:
YMMD with that ansewr! TXTessie wrote on 24/12/11:
Super exicetd to see more of this kind of stuff online.Hannah wrote on 24/12/11:
I much pferer informative articles like this to that high brow literature.Delly wrote on 24/12/11:
This does look prmosinig. I'll keep coming back for more.Liberty wrote on 24/12/11:
A provocative inishgt! Just what we need!234 wrote on 2/1/12:
Today's start off to really feel slightly bit like Groundhog Day, louis vuitton sale is not it? A few hours ago, we brought to you a story about Louis Vuitton suing a media organization for violating its trademarks, and now we have news of a provider that thinks it is a very good concept to print the visage of an Hermes Birkin on a cheap louis vuitton canvas bag: the V73 Canvas Printed Tote. The day's handbag news is downright retro. you probably could have guessed how this campaign would search louis vuitton speedy sale pale, valuable and ever so sweet. The louis vuitton sale brand tapped Steven Meisel to shoot Daria Strokous and Kati Nescher in the world's most luxurious ice cream shop, and the outcome match the mood in the louis vuitton speedy 25 clothes and accessories perfectly. Check out another shot right after the jump.the Kelly form louis vuitton neverfull MM a straightforward, arm-carried bag having a front flap closure and a major deal withlouis vuitton neverfull is often a traditional form that will not definitely belong to louis vuitton speedy 30 a lot as it belongs to handbag layout in general. Significantly like the louis vuitton luggage, the shape has reached this kind of a classic degree that attributing it to only a single business no longer seems fair. And when the reinterpretations yield bags as unique in the original since thelouis vuitton speedy Postman's Lock Satchel, I believe it is simple to see why I take that opinion