Archive for 2011

Some CakePHP usefull Tips while development


CakePHP Logo
I’ve been playing around with CakePHP for the last several days. I’m beginning to enjoy using it through the CLI (Command Line Interface) tools that comes with the framework. Maybe because I spent too much time on the command line thanks to the CR-48 (Chrome OS) developer mode :) . Anyway, here are some tips I found while learning this easy to use PHP framework:
  1. During the development, it’s a good practice to change the default value for CAKE_CORE_INCLUDE_PATH both in the index.php and test.php of webroot directory in case you forgot when deploy to the server. For example, I changed the value of this constant to $_SERVER['DOCUMENT_ROOT'] . DS . ‘cakephp’ which is converted into localhost/cakephp. Once I deployed the application to the server, the included path will change to robbychen.com/cakephp without any modification.
  2. According to the 1.2 documentation, each database has its own form control and data type relationship. For example, the tinyint data type for MySQL generates the checkbox control, whereas the boolean data type for SQLite also generates the checkbox control. It also applies to the latest stable version of CakePHP 1.3.
  3. If you want additional database options, you can download datasources plugin. This plugin also contains sqlite3 which, for some reasons, haven’t included with the CakePHP core yet. If you’re going to use SQLite in the framework without this plugin or just specify sqlite in the database config file, it will use version 2 instead.
  4. This is probably a bug in CakePHP: The CakePHP console cannot find the sqlite database file unless it’s in the root of the application folder, whereas the CakePHP web application looks for the file in the webroot directory of the application folder. The database configuration cannot be simply changed to webroot/database.sqlite. If it changes to that value, the console could find it (webroot/database.sqlite) but the web application could not (webroot/webroot/database.sqlite). The solution I decided is to make a link at the root folder to link to the sqlite file in the webroot directory. This way could both benefit the console and web application. It however does not suitable for some of you who are working on both the localhost and the production server, or often change folder, since the link target cannot be edited. The link will break once the whole directory is moved to a different machine or the target file was renamed or moved.
  5. Type cake api [type] [method] in the command line to browse through the CakePHP documentation. It is a very helpful command for use as a reference. However, you may learn some new tricks through this command, or you could use this as the primary learning resource for CakePHP assume that you already knew this command before you learn something else. For example, I found something useful for my project in the Ajax API: cake api helper ajax
I hope these tips help you to become more productive with CakePHP. If you have any questions regarding the above tips, feel free to post them in the comment below.

Posted in | Leave a comment

How to create a new Custom CakePHP Template

Custom CakePHP Template Creation


So, I hope by far you have downloaded CakePHP (A.K.A. 'Cake'), installed it, changed security settings and connected to database.

You have seen the messages in the welcome screen has changed after each of your action.

Now you will note the following:
Editing this Page

1. To change the content of this page, create: APP/views/pages/home.ctp.
2. To change its layout, create: APP/views/layouts/default.ctp.
3. You can also add some CSS styles for your pages at: APP/webroot/css.
Create DEFAULT Home Page


So, I created a new folder called 'pages' under app/views/ . And then I created a new file (using any text editor) and saved that file as 'home.ctp' under 'app/views/pages/'.

Now point your browser to:
http://caketest.local/

You can see all the messages are gone!!! You can see this is a nearly empty page!

As the name says, 'home.ctp' is the default homepage for your website. You can write anything here (with HTML tags). Those will be displayed at your homepage.

Create Default LAYOUT

Now create another new file (using any text editor) and save it as 'default.ctp' under 'app/views/layouts/' folder.

'default.ctp' is the default layout to display your content. If it is empty, CakePHP will display nothing. This is exactly what you see after saving default.ctp - a completely blank page!!!

Do not worry!

Just copy and paste the following code in the newly created 'default.ctp' file.

--: BEGIN COPY :--


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <?php echo $html->charset(); ?>
  <title>
  <?php __('My-CakePHP Tutorials'); ?>
  <?php echo $title_for_layout; ?>
  </title>
  <?php
  echo $html->meta('icon');


echo $html->css('cake.generic');


echo $scripts_for_layout;
  ?>
  </head>
  <body>
  <div id="container">
  <div id="header">
  Header Elements Will Go Here
  </div>
  <div id="content">


<?php $session->flash(); ?>


<?php echo $content_for_layout; ?>


</div>
  <div id="footer">
  Footer Text Goes Here!
  </div>
  </div>
  <?php echo $cakeDebug; ?>
  </body>
  </html>




----: END COPY :---


I have used red color to mark things you should note.
Change 'My-CakePHP Tutorials' to the title of your website. Like 'My Pet Dog Roombiq', or, anything you want.

NOTE:
There are FOUR IMPORTANT VARIABLES
$title_for_layout
$scripts_for_layout
$content_for_layout
$cakeDebug


The name suggests exactly what they do.
NOTE: 1
$title_for_layout MUST be included in between <title>  </title> tag.

<title>
  <?php echo $title_for_layout; ?>
</title>

As such, CakePHP gives a default title to every content page of your website following its own rules. But you can set a custom title as well. I'll show that in the next page.

NOTE: 2
$scripts_for_layout MUST be included before the closing </head> tag.


NOTE: 3
$content_for_layout MUST be included in between <body>
</body> tag.
<body>
<?php echo $content_for_layout; ?>
</body>

NOTE: 4
$cakeDebug SHOULD be placed before closing </body>

<?php echo $cakeDebug; ?>
</body>

AND you are done! You can add any CSS style/'div' layer to this page ('default.ctp') to give your website the layout/look you want.


For example, I tried a simple TWO Column Layout.
<div id="content">
  <div id="menu-box">
  menu items go here!
  </div>
  <div id="content-box">
<?php $session->flash(); ?>
<?php echo $content_for_layout; ?>
  </div>
</div>

I have added one div layer 'menu-box' and another one 'content-box' to display menu items and content items in two separate columns.
Now I need to add these CSS styles in a stylesheet file.

Modifying Stylesheet


As such Cake ('short-form of CakePHP) has already told us how to do that:
You can also add some CSS styles for your pages at: APP/webroot/css.
You can see the default CSS file under 'app/webroot/css' folder. The name of the file is 'cake.generic.css'. You can simply modify the content of this file (cake.generic.css).

I preferred to go to the bottom of that page and type the following lines


/* Custom CSS */


#menu-box{
width:250px;
float:left;
}
#content-box{
width:700px;
float:left;
}
It gives me a workable presentation for my custom template.

But I really need to make some more changes.

So, I just pressed (Ctrl+U) to view the source code, and I located the CSS division layers/ HTML tags being displayed in the source code, and modified them.

Here is the code: (Remember: I added the code at the bottom of cake.generic.css file.)


/* Custom CSS */
#menu-box{
width:250px;
float:left;
border-right:1px solid #CCCCCC;
}
#content-box{
margin-left:10px;
width:700px;
float:left;
border:1px solid #CCCCCC;
padding:10px;
background-color:#F3F3F3;
}
#header {
height:100px;
width:100%;
color:#000000;
background-color:#b5fad1;
font-size:2.0em;
border-bottom:1px solid #cccccc;
}
body
{
background-color:#FFFFFF;
color:#000000;
font-family:Verdana, Arial, Helvetica, sans-serif;
}

#footer
{
text-align:center;
}
..............................................................
And here is my custom template:













So, I have once again DONE that! If you are following me, you MUST have done so as well.

Congratulations!

Next, I'll try to create my 'About us' page using CakePHP. In general, I think this will give me some idea on how to create a static page with CakePHP.


Custom CakePHP Template, Cakephp Templates, Cakephp Custom Template Development

Posted in | Leave a comment

CakePHP Timezone Helper with jQuery


If you are using the updated Timezone Helper for CakePHP you can help your visitors to select a right timezone by guessing their system’s timezone and preselecting an option in the drop-down list. Insert this scriptBlock in your view:
$(document).ready(function() {
  function get_time_zone_offset( ) {
    var visitortime = new Date();
    var visitortimezone = -visitortime.getTimezoneOffset() / 60;
    var val = (visitortimezone > 0) ?
      "+" + visitortimezone.toString() + ".0":
      visitortimezone.toString() + ".0";
 
    return val;
  }
  $("#UserTimezone").val( get_time_zone_offset() );
});

Posted in | Leave a comment

How to use CakePHP Auth component login with username or e-mail


CakePHP proved to be a nice flexible and lightweight framework. When I try to bend it a little to perform something unusual it almost always turns out ok. Below an example of a custom login action that will allow users to login with their username OR e-mail. The action goes into the Users controller.
/**
 * Log in with username OR e-mail
 *
 *  @param void
 */
function login() {
 
  // login with username or e-mail
  if (!empty($this->Auth->data)) {
 
    // save username entered in the login form
    $username = $this->Auth->data['User']['username'];
 
    // find a user by e-mail
    $this->User->contain();
    $find_by_email = $this->User->find('first', array(
        'conditions' => array('email' => $this->Auth->data['User']['username']),
        'fields' => 'username'
      )
    );
 
    // found
    if (!empty($find_by_email)) {
 
      // retry login with e-mail instead of username
      $this->Auth->data['User']['username'] = $find_by_email['User']['username'];
      if (!$this->Auth->login($this->Auth->data['User'])) {
 
        // login failed
        // bring back the username entered in the login form
        $this->Auth->data['User']['username'] = $username;
      } else {
        // login successful
        // clear flash message
        $this->Session->delete('Message.auth');
 
        // redirect
        if ($this->Auth->autoRedirect) {
          $this->redirect($this->Auth->redirect(), null, true);
        }
      }
    }
  }
}
The view:
<?php echo $form->create('User', array('action' => 'login')); ?>
<fieldset>
  <legend>Login</legend>
  <?php echo $form->input('username', array('label' => 'Username or e-mail:')); ?>
  <?php echo $form->input('password', array('label' => 'Password:')); ?>
</fieldset>
<?php echo $form->end('Login'); ?>

Posted in | Leave a comment

Download Cakephp Comments Plugin Free


Comments plugin is a universal comment system that can be attached to any controller with a few lines of code. The comments plugin will allow you to make any kind of data comment-able.

Documentation

Comments Manual

The comments plugin will allow you to make any kind of data comment-able.
Comments plugin
Comments plugin is a universal comment system that can be attached to any controller with a few lines of code.
Sample of usage
We have Post model and want to have comments on the /posts/view page.
So we need to choose how we want to display the comments - flat, or as tree.
In our example we want to use the flat type comments.
First let us add the following code in the PostsController:

Posted in , | Leave a comment

Important and Useful CakePHP Plugins

When it comes to adding special functionality to a cakephp application, cakephp plugins have become the solution of choice for web developers. Awesome cakephp plugins are popping up every week, and we're always on the look out. I spent a bit of time to put together a list of cakephp plugins I found very useful. Take a look:

Socialmedia

Images/Upload

File Sharing

Other

Posted in | Leave a comment

Gallery Application using Cakephp and Jquery

Recently I’m working with CakePHP and SQLite to develop a gallery for a client. This is going to be my first CakePHP app.
While I’m working on the admin section, I wanted to allow the client to see the image once the image filename field is out of focused so that he could see if it’s the correct image.
The only JS library included with CakePHP is Prototype. Fortunately, the latest version of CakePHP (1.3.11 as of right now) allows us to include with other JS library. I included jQuery with the help of Js helper:
?

Posted in | Leave a comment

Usefull CakePHP Plugins -ACL Plugin & Facebook Plugin

I am glad to get personal emails from a few of our readers. They are mostly Cake Newbies! I am really excited to find that this blog has helped some of them. I promised to share two more plugins, which is a must have in your next Cake Project. The first one will make your life happy (if you use Auth component for authorization) and the second one will make your client happy (if he has strong facebook love!) . These two plugins are:

1) ACL plugin
2) facebook plugin


As you might know, it is easy to install plugins.

Posted in | 1 Comment

jquery UI tab in cake php

At first we have to copy all the JavaScript file inside D:\xampp\htdocs\cakephp\app\webroot\js
Here we use jquery and jquery UI javascript file and css file.
We now copy all the css file inside D:\xampp\htdocs\cakephp\app\webroot\css
Leter we will load this css and java script file.
Now Create a controller articles_controller.php inside D:\xampp\htdocs\cakephp\app\controllers
And write bellow code
01
02
03
04
05
06
07
08
09
10
11
12
13
14
<?php
class ArticlesController extends AppController {
var $uses=null;
var $name = 'Articles';
var $helpers = array('Html','Form','Javascript');
 function index() {
          $this->set('page_heading', 'Jquery Tab');      
       }
}
?>
To load JavaScript helper we write this code
1
var $helpers = array('Html','Form','Javascript');

1 Comment

Cakephp: Creating and Sending Parameters Between Controller and View

Cakephp Step By Step Tutorial: We still wok with our first application at cakephp. But we will build controller and view better. Create parameters in controller and send it to view. It will make our application more flexible.
Create a new file books_controller.php within D:\xampp\htdocs\cakephp\app\controllers. Overwrite become like this:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
    class BooksController extends AppController {
        var $Books = 'Books';
        var $uses=null;
       function index() {
          $this->set('page_heading', 'Packt Book Store');
          $book  = array (
                   'book_title'   => 'Object Oriented Programming
                                                        with PHP5',
                   'author'     => 'Hasin Hayder',
                   'isbn'        => '1847192564',
                   'release_date' => 'December 2007'
                  );
          $this->set($book);
          $this->pageTitle = 'Welcome to the Packt Book Store!';

Leave a comment

Cakephp: Installation


Cake php Step By Step Tutorial: We will learn how to install Cakephp. We will install to our local computer. Before follow this instruction, please download Cake php at www.cakephp.com.
1. Open your root web server.
2. Put cakephp downloaded.
copy zip file in htdocs folder
3. Extract it, you will get a folder named liked “cakephp-cakephp-1.3.1-0-g0180daa“.
4. For simple

Leave a comment

Tutorial - CakePHP Ajax "Quick Save" with jQuery

July 15, 2011


When you are in an administration panel, sometimes you want a “quick save” feature that allows you to save without leaving the page.Here is how to accomplish this with CakePHP and jQuery.
To start, download jQuery and the jQuery Form Plugin JavaScript . Include them in your view with the JavaScript helper:
$javascript->link(array('jquery', 'form'), false);
Include the RequestHandler in your controller detect an Ajax save attempt.Also include the JavaScript helper if you haven’t already.
var $helpers = array('Javascript'); 
var $components = array('RequestHandler');
Next we want to override our save function with the ajax quick save.Put this right before your $this->Model->save($this->data) in your save action.
if ($this->RequestHandler->isAjax()) { 
  if ($this->Article->save($this->data)) { 
    echo 'success'; 
  } 
  Configure::write('debug', 0); 
  $this->autoRender = false;
  exit(); 
}
This detects if the request is ajax, then saves the data. Then it sends back a simple, “success” message to let you know things went fine. It also writes debug to 0 and doesn’t render anything, then exits.
Lastly, lets create and include a JavaScript file that performs the quick save.
jQuery(function($){ 
  $('<input type="button"value="Quick Save"/>') 
    .click(function(){ 
      $(this).parents("form:first").ajaxSubmit({ 
        success: function(responseText, responseCode) { 
          $('#ajax-save-message').hide().html(responseText).fadeIn(); 
          setTimeout(function(){ 
            $('#ajax-save-message').fadeOut(); 
          }, 5000); 
        } 
      }); 
      return false; 
    }) 
    .appendTo('form div.submit'); 
});
This adds a button called, “Quick Save” to each form on the page where a div with class="submit" exists (you may want to switch this to the id of the form you want to add quick save to). Then It also attaches a click event to the button that submits the form via the jQuery Form Plugin.
In a few simple steps, we’ve created a quick save feature that saves your data whenever you want without leaving the page.

Posted in | Leave a comment

Full CakePHP Application Part 1

This is the first article in a series that I will use to document the process of creating a fully featured web application in CakePHP. At the moment the whole series comes in at around 8 articles but I'm sure this will grow as I write up each one. My aim is to publish one article a week detailing the steps involved with setting up and coding a full working online DVD Catalog Application that will keep track of all my DVDs. I've been meaning to create such an application for a long time so I thought it would be a great project to put on my website.
In this first article I'm going to go through the steps of setting up your new CakePHP project, go through the requirements of the system, create the database structure and finally setup the Model's and associations. For this project I'm going to be using the newest 1.2 version of CakePHP, I haven't used it before so this will be a learning process for me as well.

Brief

With any new application I'm working on I like to outline a pretty simple brief or overview of what I want the app to achieve along with some of the functionality that the app will offer. For my DVD Catalog I want an application that will manage my ever growing collection of DVDs ( films and TV shows ). For each DVD that is entered into the application I want to add an image ( preferably a cover image ), a website URL, the Imdb website entry and a personal rating.
Along with being able to add / edit / delete DVDs I would like a front end display so that other people can go online and browse my collection as well. This front end will have search and filter functionality so that I can search by name or filter by format type etc. The front end also needs to be fully customisable so I'm going to implement a templating system where I can easily change the layout in the admin panel.

Requirements

Good planning is paramount to any system so here are the requirements for the DVD Catalog Application:
  • Formats
    • These are the different formats of DVD that will exist in the system.
    • A few examples of format types include dvd, dvdcopy, dvdrip, tvrip and hd.
    • Be able to add / edit / delete format types.
    • Be able to sort and filter DVDs by format type.
  • Types
    • These are the different types of DVD in the system.
    • Examples include Films and TV Shows.
    • Be able to add / edit / delete types.
    • Be able to sort and filter DVDs by Type.
  • Locations
    • These are the different locations where your DVDs will be stored.
    • Examples include spindle 1, spindle 2, etc.
    • Be able to add / edit / delete locations.
    • Be able to sort and filter DVDs by Location.
  • DVDs
    • These are the actual DVDs that you will enter into the system.
    • Each DVD will have a number of attributes:
      • The Format Type, is it a DVD? a Copied DVD? A DVD Rip?.
      • The Type, is it a Film? Is it a TV Show?
      • The Location.
      • Name.
      • Image URL.
      • Official Website.
      • Imdb Link.
      • Rating.
      • Number of Discs.
      • Number of Episodes if its a TV Show.
  • Genres
    • A DVD will be able to belong to a number of genres.
    • A Genre will have multiple DVDs.
    • An Admin will be able to add /edit / delete Genres from the system
    • A user will be able to:
      • Filter by Genre.
      • Search by Genre.
  • Admin Section
    • The application will have a password protected admin area where a logged in admin will be able to interact with the system.
    • Admins can add / edit / delete:
      • Formats
      • Types
      • Locations
      • DVDs
      • Templates
  • Front End
    • The application will have a front end that will be viewable to anyone.
    • The main front end will show all the DVDs in the system.
    • The number of displayed DVDs will be limited and so pagination will be required.
    • A user will be able to filter the DVDs by:
      • Format
      • Type
      • Location
      • DVD Rating
    • A user will also be able to search for DVDs.
    • A user will be able to bookmark search and filters.
    • A user will be able to select different templates, changing the appearance of the system.
  • Templates
    • The system will be able to incorporate numerous templates.
    • A template will be added by the admin of the application
    • The template name will be used to identify images and css used by the template
    • A user will be able to select the template to change the design.
Although I've tried to be as thorough as possible with the requirements at this early stage a few may be added during development. Going through the requirements before building an application will give you a good idea of how the system should work and how it all fits together. It also helps with the database design process and give you an idea of what tables you will need and the types of associations that the tables have with each other.

Database Structure

From the list of requirements I've come up with 8 different tables for the database which include Formats, Types, Locations, DVDS, Genres, Templates and Admins.
  • Formats
    • id, name, slug, description, created, modified, status
  • Types
    • id, name, slug, description, created, modified, status
  • Locations
    • id, name, slug, description, created, modified, status
  • DVDs
    • id, format_id, type_id, location_id, name, slug, image, website, imdb, rating, discs, episodes, created, modified, status
  • Genres
    • id, name, slug, created, modified, status
  • DVDS_Genres
    • id, dvd_id, genre_id
  • Templates
    • id, name, layout_name, description, image, created, modified, status
  • Admins
    • id, username, password, last_login, status
First create the new database either using PhpMyAdmin or by using this statement:
  1. CREATE DATABASE `dvdcatalog`;  
Formats, Types and Locations have exactly the same database fields but I've not combined them into one table and used a flag to identify them because I wanted to seperate out the logic for each type and it also makes it easier to sort and filter by the different tables when our system is up and running. The model associations between these tables and the DVD table will also be easier to maintain and establish. A "slug" has been entered that will be used for user friendly URLs so instead of seeing "/formats/view/1" you will see "/formats/view/dvdrip".

CREATE TABLE `formats` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`desc` TEXT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);
CREATE TABLE `types` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`desc` TEXT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);
CREATE TABLE `locations` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`desc` TEXT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);

The DVD table will store all our information for each DVD and will also contain "foreign keys" that will link a DVD to a Format, Type and Location.

CREATE TABLE `dvds` (
`id` INT NOT NULL AUTO_INCREMENT ,
`format_id` INT NOT NULL ,
`type_id` INT NOT NULL ,
`location_id` INT NOT NULL ,
`name` VARCHAR( 100 ) NOT NULL ,
`slug` VARCHAR( 100 ) NOT NULL ,
`image` VARCHAR( 255 ) NOT NULL ,
`website` VARCHAR( 255 ) NOT NULL ,
`imdb` VARCHAR( 255 ) NOT NULL ,
`rating` TINYINT NOT NULL ,
`discs` TINYINT NOT NULL ,
`episodes` TINYINT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);

The Genre table will contain the name of the Genre along with a slug for friendly URLs. A Join table will also be needed to link up Genres with DVDs, this will be displayed in much more detail in our model associations but this allows DVDs to have multiple Genres and to allow a Genre to have multiple DVDs.

CREATE TABLE `genres` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);

CREATE TABLE `dvds_genres` (
`id` INT NOT NULL AUTO_INCREMENT ,
`dvd_id` INT NOT NULL ,
`genre_id` INT NOT NULL ,
PRIMARY KEY ( `id` )
);
The templates table will store all the information relatating to the template, the layout name will be used to choose the images that the template will use along with the css file that will change the look and appearence of the front end system.

CREATE TABLE `templates` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  `layout_name` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `image` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`id`)
);

The final table (admins) will be used to store the username and password of any user that has access to the admin area of the application.

CREATE TABLE `admins` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `last_login` datetime NOT NULL,
  `status` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`id`)
);

Using CakePHP conventions our database table names are all plural and our join table is the plural names of the two tables in alphabetical format. This ensures that CakePHP will automatically be able to connect to the database and create associated data with Cake's inbuilt Automagic methods.

Setting up CakePHP

First thing to do is download the latest version of CakePHP at the time of writing this is currently 1.2.0.6311. I do all my development locally using Xampp and I'm going to setup a virtual host so that I can simulate an online enviornment. For information on how do this please visit my previous article on setting up a local web server and using virtual hosts.
Now I have created my virtual host called "dvdcatalog" and I've extracted CakePHP 1.2 beta to the directory. To check that everything is working goto "http://catalog" and you should be greeted with the default screen.
CakePHP DVD Catalog Application Image 1 The first thing its telling us to do is change the value of "Security.salt" in app/config/core.php, so open up core.php and change the default value of the security.salt variable. I've used this excellent website to generate a random string.

// app/config/core.php line: 153

Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');

Whilst I have the core.php file open I've changed the security setting from high to low for development purposes so that I can stay logged in longer. Note that I need to change this back when the system is live. I've also enable admin routing, which will allow us to easily create an admin section, this will be discussed in detail later in development.


// app/config/core.php line: 149

// from
Configure::write('Security.level', 'high');
// to
Configure::write('Security.level', 'low');

// uncomment this line:69
Configure::write('Routing.admin', 'admin');

CakePHP DVD Catalog Application Image 2 Now we need to make sure that our application can connect to the database, the default cake screen is telling us that the database configuration file is not present and that we need to rename the file located in the config folder. Open up your renamed "database.php" file and enter your database username, password and table name.

var $default = array(
    'driver' => 'mysql',
    'persistent' => false,
    'host' => 'localhost',
    'port' => '',
    'login' => 'username',
    'password' => 'password',
    'database' => 'dvdcatalog',
    'schema' => '',
    'prefix' => '',
    'encoding' => ''
);


Reload the application in your browser and if everything went well CakePHP can now connect to your database.
CakePHP DVD Catalog Application Image 3

Creating the Model files and Associations

The next stage is to create the model files for the system and setup the associations between the tables. Before you go any further please read and re-read the Associations section of the Models chapter in the manual. This section is essential to understanding how tables relate to each other.
From our database tables we have a number of relationships:
  • A DVD belongs to:
    • A Format
    • A Type
    • A Location
  • A DVD has and belongs to many:
    • Genres
  • A Format has many:
    • DVDs
  • A Type has many:
    • DVDs
  • A Location has many:
    • DVDs
  • A Genre has many and belong to:
    • DVDs
With a "belongsTo" relationship we need to specifiy the foreign key in the database and so each DVD in the database has a format_id, type_id and location_id that will relate to the primary key of the coresponding table. A "hasAndBelongsToMany" is a special type of association that requires an extra "join" table, this is because a DVD an belong to many genres and a single genre can have many DVDs. This is also called a "many-to-many" relationship and the extra table keeps track of all the associations. The beauty of using CakePHP is that if your database and associations are setup correctly the finding and saving of related data will be done automatically for you, which makes the development process much easier.
Generally you have a model file for each of the tables in the database so here are the files:
/**
 * file: app/model/dvd.php
 *
 * Dvd Model
 */
class Dvd extends AppModel {
    // good practice to include the name variable
    var $name = 'Dvd';
 
    // setup the belongs to relationships
    var $belongsTo = array(
        'Format'=>array(
            'className'=>'Format'
        ),
        'Type'=>array(
            'className'=>'Type'
        ),
        'Location'=>array(
            'className'=>'Location'
        )
    );
 
    // setup the has and belongs to many relationship
    var $hasAndBelongsToMany = array(
        'Genre'=>array(
            'className'=>'Genre'
        )
    );
}

/**
 * file: app/model/format.php
 *
 * Format Model
 */
class Format extends AppModel {
    // good practice to include the name variable
    var $name = 'Format';
 
    // setup the has many relationships
    var $hasMany = array(
        'Dvd'=>array(
            'className'=>'Dvd'
        )
    );
}

/**
 * file: app/model/type.php
 *
 * Type Model
 */
class Type extends AppModel {
    // good practice to include the name variable
    var $name = 'Type';
 
    // setup the has many relationships
    var $hasMany = array(
        'Dvd'=>array(
            'className'=>'Dvd'
        )
    );
}

/**
 * file: app/model/location.php
 *
 * Location Model
 */
class Location extends AppModel {
    // good practice to include the name variable
    var $name = 'Location';
 
    // setup the has many relationships
    var $hasMany = array(
        'Dvd'=>array(
            'className'=>'Dvd'
        )
    );
}

/**
 * file: app/model/genre.php
 *
 * Genre Model
 */
class Genre extends AppModel {
    // good practice to include the name variable
    var $name = 'Genre';
 
    // setup the has and belongs to many relationship
    var $hasAndBelongsToMany = array(
        'Dvd'=>array(
            'className'=>'Dvd'
        )
    );
}


/**
 * file: app/model/template.php
 *
 * Template Model
 */
class Template extends AppModel {
    // good practice to include the name variable
    var $name = 'Template';
}

Wrapping Up

Ok so I've covered quite a lot of ground in the first article from an inital brief I've created a number of requirements for the system and from those I've created a database structure that hopefully won't change much as I create the system. I've downloaded and installed the latest version of CakePHP to a virtual host on my local development setup so when the time comes to migrating the system online it should be relatively easy. From the database tables I've created the Model files and setup the associations between them, initially these have been configured to the minimum but as the application progresses I will be covering the more advanced features.
At the moment the application doesn't do anything but this will soon change as I add new features and functionality over the upcoming weeks. What I have done is gone through the process of starting a new project and the planning and thinking that needs to go into a project before you even start coding. With a strong base of requirements and a well thought out database design your application will be easier to code & maintain and the time spent at this stage will save you time in the later stages of development.

Posted in | Leave a comment