This is a tutorial on how to design a website from scratch using CakePHP. To make the tutorial useful and challenging, I decided to clone an existing web application. One web app that I visit every day is http://news.ycombinator.com/. Y.News is a great resource for startups and it is based on Reddit.com.
To accelerate the development cycle, I copied Y.News’s .css file and HTML structure.
All that is left is the dynamic code (php) including database connection, user authentication, etc…
I first started by designing the database and followed CakePHP naming conventions. I have four tables: users, sites, comments and votes. ‘Users’ has many sites, comments, and votes; and ‘sites’ has many comments and votes.
Then I ran cakePHP’s bake.php to build the default models, controllers, and views.
Then I designed the website structure:
/sites/newest
/sites/best
/sites/submit
/sites/view
/users/add
/users/login
/users/view
/layouts/default
/errors/error404
To make the website more efficient, I added two fields, commentscount and votescount, to the sites table and updated those fields every time a new comment or a new vote is added. This saved me two additional JOIN queries.
Then I deleted all unnecessary model relationships, controller functions, and views. Most importantly, is deleting unnecessary model relationships, for example, the relationship between the votes table and the sites table is no longer needed after adding the votescount field to the sites table. Deleting relationships saves you a JOIN query.
Sometimes you will be forced to add a JOIN query. For example, /sites/view displays one site and all related comments, to show the username of the comment submitter, you will need to add a new query:
Sites.*, Comments.*, Users.username AS Auther FROM Comments INNER JOIN Users ON Users.id = Comments.user_id LEFT OUTER JOIN Sites ON Comments.site_id = Sites.id WHERE Sites.id = ‘. $id
This website was built in 4 hours; that is a lot given that this is a simple website. CakePHP is awesome if you are familiar with the API, if not it might be a bit frustrating to learn it all, but trust me it is all worth it. For example, to display the time elapsed since a site was added, you could use: $time->relativeTime($site['Site']['created']), now that is awesome!
Here are few screenshots and the source code:




Code:cakephp-tutorial-projectrar.pdf (right click, save as, rename extension to .rar)
SQL: cakephp-tutorial-projectsql.pdf (right click, save as, rename extension to .sql)