Getting Baked With CakePHP

What Is CakePHP?

CakePHP is a PHP open source rapid development framework that was born in 2005, it is distributed under an MIT licence and has a very active community. So of its other features include:

  • Compatibility with PHP4 and PHP5
  • Integrated CRUD for database interaction and simplified queries
  • Model View Controller (MVC) Architecture
  • Request dispatcher with good looking, custom URLs
  • Built-in Validation
  • Fast and flexible templating (PHP syntax, with helpers)
  • View Helpers for AJAX, Javascript, HTML Forms and more
  • Security, Session, and Request Handling Components
  • Flexible access control lists
  • Data Sanitation
  • Flexible View Caching

In this post i will run the reader through the process of setting up CakePHP and then creating a simple notice board application to demonstrate the simplicity of writing an application with cake.

Installing CakePHP

Download the latest copy of CakePHP from www.CakePHP.org uncompress and place in the root directory of your web server. Check that the Apache <directory> option for the root directory contains the AllowOverride option and it is set to "ALL" i.e

<Directory /mypath/tocakephp/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>

You must also ensure that Apache is using the rewrite mod to enable this on my Ubuntu based server system i used the command a2enmod rewrite. After all your changes to the Apache configuration have been made restart the Apache service so the changes take affect.

Depending on how you configured Apache you may run into some trouble with the rewrite functionality, have a look at the web server URL in a browser, if the CakePHP page you see is missing its CSS and images something is amiss. You have two options with how you want to move forward from this point, you can uncomment line 40 of the CakePHP config file (app/config/core.php) which will work around the malfunctioning rewrite mod plugin. Or you can look at this page on the CakePHP site, which has some pointers on fixing the problem properly.

Also you must make sure Apache has write access to the app/tmp directory and its sub folders before. A new MySQL database named notice_board will have to be created using PHPmyadmin or similar to hold the data for our sample application.
After this is done the file app/config/database.php.default needs to be renamed to app/config/database.php. Using a text editor the database parameters in the file then need to be changed to match your MySQL setup and the changes saved.

CakePHP after initial setup

Baking Your First Application

Now the framework is installed we can start work on our first CakePHP application its going to be a simple notice board, it wont have all the bells and whistles but it will show you how quickly, and easily some tasks can be accomplished using cake.
First up you will need to make a table in the database you created earlier to hold our notices.

CREATE TABLE `notice_board`.`notices` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
`title` VARCHAR( 255 ) NOT NULL ,
`content` TEXT NOT NULL ,
`created` VARCHAR( 30 ) NOT NULL ,
`modified` VARCHAR( 30 ) NOT NULL ,
PRIMARY KEY ( `id` )
);

** Note: it is CakePHP convention to use plural names when naming database tables. All tables should also have a field named "id" as the primary key.

Creating The Model

In CakePHP each database table should have its own model, this model is basically just a class and is used to access and modify the data stored within the table. To create a model for the notices table create a file named notice.php in the app/models folder. In this file enter:

<?php
class Notice extends AppModel {
var $name='Notice';
}
?>

You can see from the code above the Entry calls extends the AppModel class, in CakePHP all models extend this class.

**Note: It is also a CakePHP convention that the model class its file name is a singular version of database table name.

Creating The Controller

The controller is a piece of code that decides what has to happen within an MVC application. Every model in an application needs an associated controller. Creating a controller for the notice board application is very similar to creating the model. Just create a new file named notices_controller.php in the app/controllers directory.

In this file enter the following code:

<?php
class NoticesController extends AppController {
var $name = 'Notices';
function index() {
$this->set('notices', $this->Notice->findAll());
}
}
?>

The addition of the index function is a method to give our controller some functionality in this case to display all of the notices stored in the database.

**Note:
It is CakePHP convention that controller names are plurals of the model name.

 

Creating A View

We have a model, a database and a controller so now we need a view to display our hard work to the end user. Create a new directory  called notices in the folder named app/views. Now create a file within the newly created directory called index.thtml containing the following code:

<h2>Notice Board</h2>
<p><?PHP echo $HTML->link('Add New Notice', '/notices/add'); ?></p>
<div style="height: 10px;"></div>
<?PHP if(empty($notices)) : ?>
This notice board currently has no notices to display.
<?PHP
else:
foreach ($notices as $notice):
echo '<b>Title:</b> ' . $notice['Notice']['title'] . '<br>';
echo $notice['Notice']['content'] . '<br>';
echo '<b>Created: </b><i>' . $notice['Notice']['created'] . '</i><br>';
echo $HTML->link('Delete', "/notices/delete/{$notice['Notice']['id']}", null, 'Are you sure?'  );
echo '<br><div style="height: 10PX;"></div>';
endforeach;
endif;
?>

**Note: The 1.2 version of CakePHP will use the file extension .ctp as opposed to the extension .thtml usedfor  "views" in the earlier versions.

Now if you aim your browser at your server's url with the trailing name "notices" i.e http://mysever.com/notices, you should be able to now see that we are making some positive progress with our app.

Viewing The notices on the CakePHP app

Creating New Notices

Since we have laid out the ability to view notices its time to add some functionality to the controller so a user can actually post notices to the board. To achieve this you will need to edit the notices_controller.PHP and append an add function, so the files contents look like this:

<?PHP
class NoticesController extends AppController {
var $name = 'Notices';
function index() {
$this->set('notices', $this->Notice->findAll());
}

function add() {
if (!empty($this->data)) {
if ($this->Notice->save($this->data)) {
$this->flash('Your notice has been posted.','/notices');
}
}
}
}
?>

Now create a template named app/views/add.thtml with the code below for the user to enter the details of a new notice.

<h2>Create Notice</h2>
<form method="post" action="<?PHP echo $HTML->url('/notices/add')?>">
<div align="center">
<p>
Notice Title:
<?PHP echo $HTML->input('Notice/title', array('size' => '40'))?>
<?PHP echo $HTML->tagErrorMsg('Notice/title', 'A notice title is required.') ?>
</p>

<p>
Notice Body:
<?PHP echo $HTML->textarea('Notice/content', array('rows'=>'10')) ?>
<?PHP echo $HTML->tagErrorMsg('Notice/content', 'Your notice needs some content.') ?>
</p>

<p>
<?PHP echo $HTML->submit('Create Notice') ?>
</p>
</div>
</form>

Adding new notices to the CakePHP App

Form Validation

Since the application has a form to accept data from a user the entered data will have to be validated, one of CakePHP's strong points is its built in validation functionality removing a lot of pain for developers.
To handle the validation of our new notice you need to go back and edit the entries model (app/models/notice.PHP) and append a validate array so the file looks like this:

<?PHP
class Notice extends AppModel {
var $name='Notice';
var $validate = array(
'title' => VALID_NOT_EMPTY,
'body' => VALID_NOT_EMPTY
);
}
?>

Deleting Existing Notices

Now notices can be added to the board, it makes sense to add functionality supporting the deletion of a notice. To achieve this we need to add a new function to our controller so the delete link on the index page works properly. Open the controller file back up and add a delete function so the file contents are the same as below:

<?PHP
class NoticesController extends AppController {
var $name = 'Notices';
function index() {
$this->set('notices', $this->Notice->findAll());
}

function add() {
if (!empty($this->data)) {
if ($this->Notice->save($this->data)) {
$this->flash('Your notice has been posted.','/notices');
}
}
}

function delete($id) {
$this->Notice->del($id);
$this->flash('The selected notice has been deleted.', '/notices');
}

}
?>

You should now be the proud owner of your first working CakePHP web application!

Notice Views CakePHP Notice Board

Further Reading

CakePHP (Official Site)
http://www.cakephp.org/

A Run Down On The Conventions In CakePHP
http://book.cakephp.org/view/22/CakePHP-Conventions

Understanding MVC (On the CakePHP site)
http://book.cakephp.org/view/11/Overview

Model View Controller - Background, History etc on Wikipedia
http://en.wikipedia.org/wiki/Model-view-controller

 

 

Vote Result

----------
Score: 0.0, Votes: 0

Back to top