CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.
This tutorial will give you a good start in the world of CakePHP, just to learn the basics of the framework. The official CakePHP Blog tutorial (For Cake 1.1) gives you a good idea, but this tutorial will take it a couple of steps further (and in the next parts way beyond the official tutorial). Don't worry: This article will perfectly guide to making your first steps on baking some code.
Download the source code I created directly if you don't want to write anything yourself, but still want to learn. I do recommend you to read the full article to understand the whole code. Take note that this tutorial is written for Cake version 1.2 (Using 1.2.0.7692 RC3 to be precise).
Download Source code
This tutorial will give you a good start in the world of CakePHP, just to learn the basics of the framework. The official CakePHP Blog tutorial (For Cake 1.1) gives you a good idea, but this tutorial will take it a couple of steps further (and in the next parts way beyond the official tutorial). Don't worry: This article will perfectly guide to making your first steps on baking some code.
Download the source code I created directly if you don't want to write anything yourself, but still want to learn. I do recommend you to read the full article to understand the whole code. Take note that this tutorial is written for Cake version 1.2 (Using 1.2.0.7692 RC3 to be precise).
Download Source code
The setup
First, download and install the latest release of Cake
For the database, we're going to use the following MySQL script. You can execute this in your phpMyAdmin.
CREATE TABLE IF NOT EXISTS `blogs` ( `id` int(255) NOT NULL auto_increment, `date` date NOT NULL, `title` varchar(255) NOT NULL, `introtext` text NOT NULL, `maintext` text NOT NULL, PRIMARY KEY (`id`) )
We'll now fill the database with some sample data.
INSERT INTO `blogs` (`id`, `date`, `title`, `introtext`, `maintext`) VALUES (1, '2008-10-24', 'My first blog post', '<h1>Hello World!</h1>\r\n<p>This is my first article using the CakePHP framework. I hope you like it.</p>', '<h2>This text will only be visible on the second page.</h2>\r\n<h3>It''s just like how <a href="http://joomla.org/" title="Joomla! CMS">Joomla!</a> works!</h3>'), (2, '2008-10-27', '2nd article', '<p>This is my second article, just to test the amazingly cool CakePHP framework.</p>', '<p>Even the <em>read more</em> works!</p>'), (3, '2008-11-02', 'Last article', '<p>Sorry guys, this will be my last article. Make sure you check out <a href="http://www.marcofolio.net/" title="Marcofolio">Marcofolio</a> for more interesting articles!</p>', '<p> And in the future: Making this blog bigger & better!</p>');
OK, all preperations are made: Let's get down to business and code some PHP. Comments are addedin some sections to explain what the code does.
Clearing the errors
We can easily create a blog in the
/blog/
section of the site (The URL will look like this: http://yourdomain.com/blog/). You must remember the syntax of an URL for CakePHP: http://yourdomain.com/CONTROLLER/FUNCTION/ARG1/ARG2/ etc. Anyway, when you now visit the/blog/
section of your site, you'll see the following error (with the default download package).
What a nice error message! It's telling us that Cake is missing the BlogController, together with the filename it's searching for and the default code. Let's follow this error message by creating a "blog_controller.php" file in the
app/controllers
directory. This file will have the following code:<?php class BlogController extends AppController { var $name = 'Blog'; // Used when indexing the page (http://yourdomain.com/blog/) function index() { } } ?>
When done correctly, the following error should show up: The view is missing.
To fix this problem, go to your
app/views
folder. Create a new folder called blog inside of the views folder. Inside the /blog/
folder, create a file called index.ctp
(CTP = Cake Template). Leave the file empty for now.
Pfew, all of the errors are gone now. Now we can really start writing some code.
The "Blog" model
The model in a MVC-pattern (Model-View-Controller) represents the storage type. In Cake, the model is the final place before data enteres the actual database (or the first when data is retrieved from the database). We want to create a Blog model to retrieve Blog data from the database.
To achieve this, create blog.php inside the
app/models
folder. This file will contain the following code:<?php class Blog extends AppModel { var $name = 'Blog'; var $primaryKey = 'id'; } ?>
Now we'll have to "tell" the controller to use the model. To do so, add the following line to your
blog_controller.php
, right under the $name
variable.var $uses = array('Blog');
To check if the controller is now connected to the model, change your
blog_controller.php
and add the following inside the index()
function:debug($this->Blog->findAll());
This code will ask the Blog-model to do a "findAll()" (standard model function in CakePHP) to retrieve all the data the model can get from the database (in this case: Everything from the "blogs" table). The debug() function will give you a human readable output to check your output.
When you now visit your blog (http://yourdomain.com/blog/), you should be able to read all information from the "blogs" table in your database in several arrays. If so, we can move on!
Controller to view
The controller now has a connection with the correct model. Now we'll need to connect the controller information with the view. To do so, add the following line to your
index()
function of blog_controller.php:$this->set('articles', $this->Blog->findAll());
Now the "articles" variable for the object "Blog" will contain all blog posts retrieved from the database. Open the index.ctp file, located in
views/blog
. To test if it worked, add the following line to the file:<?php debug($articles) ?>
When you now view the page in your browser (http://yourdomain.com/blog/), you should once again see all articles in the form of an array. There is one difference from the previous version tough: You're now getting the data from the view.
Delete the "debug()" in your index.ctp file to create a real view. This is how a view for the blog could look like.
<div id="blog"> <?php foreach ($articles as $article) { ?> <div class="article"> <h1><a href="blog/index/<?= $article['Blog']['id'] ?>" title="<?= $article['Blog']['title'] ?>"><?= $article['Blog']['title'] ?></a></h1> <p class="date"><?= $article['Blog']['date'] ?></p> <p><?= $article['Blog']['introtext'] ?><a href="blog/index/<?= $article['Blog']['id'] ?>" title="<?= $article['Blog']['title'] ?>" class="readon">Read more...</a></p> </div> <?php } ?> </div>
When you now look at your
/blog/
, you would now be able to really see your blog alive! This is starting to get somewhere, doesn't it.
The "view" parameter
As you now can see, the title and the "read more..." are linked to the following URL:
http://yourdomain.com/blog/ID
, where ID is the ID of the article. This is the URL to show the full article.
To make this work, we'll need to make changes to the controller and add a view. We'll start with the controller, so open blog_controller.php. Make the following changes to your
index()
function:function index($view = null) { // What to do if a view is set if (isset($view)) { $this->set('article', $this->Blog->find("id = $view")); $this->render('article'); } else { $this->set('articles', $this->Blog->findAll()); } }
Let me get into some detail on this one. The
$view = null
tells CakePHP that this parameter is optional. Using isset()
you can check if the $view paramter has been set. If none is found, we'll do afindAll()
on the model to retrieve all data and render the index.ctp
view.
If the view is set, we'll find the article by using the ID (by asking it to the model) and we'll render the "article" layout. "But there isn't an article layout?" I hear you say. Correct: We'll need to create it. So, create a article.ctp inside the
app/views/blog/
folder. Use the debug($article)
function to check if the article is loaded.
Assuming everything went well, we can now create the layout for the "article" view. This is how it could look like.
<div id="article"> <h1><?= $article['Blog']['title'] ?></h1> <p class="date"><?= $article['Blog']['date'] ?></p> <p class="intro"><?= $article['Blog']['introtext'] ?></p> <p class="main"><?= $article['Blog']['maintext'] ?></p> </div>
When you now visit the page that contains all the articles (
http://yourdomain.com/blog/
) and click on one of the titles (or the "read more..." link), you should be able to see the full article (http://yourdomain.com/blog/index/1
, where 1 is the ID of the article).
Altering the layout & Styling with CSS
So far, we've been using the default layout that comes with CakePHP and no CSS styling was used. Let's change that, making it our real own blog.
We already know that our code is working, so we'll not need to debug anymore or see the queries executed. Open
core.php
located in app/config
. Search for Configure::write('debug', 2);
and change the "2" to a "0".
Create a new layout file called default.ctp in the
app/views/layouts
folder. Add the following code to that file.<html> <head> <title>My first CakePHP blog</title> <?= $html->css('default'); ?> </head> <body> <?= $content_for_layout ?> </body> </html>
Make sure you add the DOCTYPE and xmlns etc. to make it valid. In the download code it is set correct, but I had to trim it down here a bit.
Anyway, when you now view your blog (single article and total view) in your browser, you should be able to only see plain HTML (no fancy stuff) since we did't add it. The
$html->css('default');
inside the HEAD of default.ctp will create a URI to the "default.css". We didn't make this file (yet), so let's do this in order to style it.
Create default.css inside the
app/webroot/css
folder. This is the place to put all the CSS at this moment. Remember we had two ID's: #blog and #article. I added the following CSS:/* HTML */ body { background-color:#003333; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color:#CCCCCC; } a { color:#FFCC33; } /* Classes */ .date { float:right; color:#333333; } .readon { background-color:#009966; border-style:solid; border-color:#000000; color:#FFCC33; padding:2px; font-size:10px; } /* Blog */ #blog { width:500px; margin-left:auto; margin-right:auto; padding-top:15px; } #blog .article { background-color:#336666; padding:5px 10px 10px 10px; } #blog .article h1 a { color:#FFCC33; text-decoration:none; } #blog .article h1 a:hover { text-decoration:underline; } /* Article */ #article { width:500px; margin-left:auto; margin-right:auto; margin-top:15px; background-color:#336666; padding:5px 10px 10px 10px; }
Now I'm sure that there are loads of designers out there that can make this CSS and layout way more fancy, but I hope you get the idea. This article is written for the code, not for the layout.
Conclusion / Download
There we have it: A fully functional blog that gets his data from the database. Try adding something to the database to see another article added.
Happy baking!
Nice article I was really impressed by seeing this blog, it was very interesting and it is very useful for me.Informative blog! it was very useful for me.Thanks for sharing
ReplyDeleteCakePHP Development Company
My recommended editor for CakePHP is Codelobster
ReplyDelete