Start Cakephp – How to use shell/console/bake

Before Start

This will give an idea to start with cakephp. Here are some details of how to install cakephp, baking a simple application to add, view, edit, delete data with cakephp 1.3.

Before that, read something about,
MVC – Model-View-Controller : http://book.cakephp.org/view/10/Understanding-Model-View-Controller
Cakephp Conventions – http://book.cakephp.org/view/22/CakePHP-Conventions

Step 1: Download and install cakephp

Go to http://github.com/cakephp/cakephp/archives/1.3 and download cakephp 1.3. Extract the files, it will give a folder starts with cakephp. Rename and place this folder in the php development area. For example, rename the folder as project1, if using xampp place it in the htdocs folder. Now open the url – http://localhost/project1/. Following page will show:

cakephp-default-page

cakephp-default-page

1. First notice says to change the salt value: Open file project1/app/config/core.php, change the value in line Configure::write(‘Security.salt’, ‘change-this-value-add-some-letters’).
2. Next cipherSeed – same file, line – Configure::write(‘Security.cipherSeed’, ‘change-this-add-some-number’).
3. Make sure app/tmp directory is writeable.
4. Then make database setup – change file name app/config/database.php.default to database.php and set database access variables. Here shows connection to cakedb database with username root and blank password.

var $default = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => '',
        'database' => 'cakedb',
        'prefix' => '',
);

Now try reload the page http://localhost/project1/ – will show full of green bars, Then it means everything is ok.

Step 2: Setup for baking

(If you are able to run php.exe and cake.bat in command line skip this step)
To use cakephp console, run the console file using php.exe. To make it easier do
1. Right click on MyComputers > Properties > Advanced Tab > Environment variables
2. In System variables > select Path > Edit
3. Enter the path for the php.exe file and cake.bat file separated with semicolon. If using xampp in c drive the paths will be c:\programfiles\xampp\php;c:\programfiles\xampp\htdocs\project1\cake\console;

cakephp-console-setup

cakephp-console-setup

Now we are ready to bake. To check, open command line, cd to the project1 folder and type cake, you will see the following:

cakephp-test-console

cakephp-test-console

Step 3: Baking the cake

Consider creating an application with departments, students tables (Students in particular departments).
1. First create that tables in database.

CREATE TABLE IF NOT EXISTS `departments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `email` varchar(200) NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

2. Back to the command prompt, confirm you are in the current project1 path. Then execute
cake bake all
3. Enter the number for the corresponding modal (Here console will ask 1. Department, 2.Student), first give 1 and enter. It will ask for unit test twice, give No.

cakephp-bake-cake

cakephp-bake-cake

4. Like this bake students model.

Step 4: What is baked

You can find these new files/folders are baked magically:
1. Models: app\models\department.php and app\models\department.php
2. Controllers: app\controllers\departments_controller.php and app\controllers\students_controller.php
3. Views: app\views\departments\add,edit,index,view and app\views\students\add,edit,index,view ctp files
Recall the MVC and naming conventions here.
View, add, edit, delete, validations and relations everything will be backed in the above method.

Step 5: Understanding and further

First understand the execution of the urls in cakephp.
Normally the url of the cakephp looks like this: http://localhost/project1/controller/method/parameter
The url http://localhost/project1/students/view – will call the view method in the students controller. After executing the method views/students/view.ctp will be automatically rendered.

Now can access the departments data by: http://localhost/project1/departments/index.
To add: http://localhost/project1/departments/add.
Also note the related actions are backed too.

1. Validations
Consider the following lines in models.

//in student model
var $validate = array(
        'department_id' => array(
                'numeric' => array(
                        'rule' => array('numeric'),
                ),
        ),
        'name' => array(
                'notempty' => array(
                        'rule' => array('notempty'),
                ),
        ),
        'email' => array(
                'email' => array(
                        'rule' => array('email'),
                ),
        ),
);

These set the validations while adding/editing data. Change these according to need.

2. Relationships
Consider these lines

//in department.php model
var $hasMany = array(
    'Student' => array(
            'className' => 'Student',
            'foreignKey' => 'department_id',
            'dependent' => false,
    )
);

//in student.php model
var $belongsTo = array(
        'Department' => array(
                'className' => 'Department',
                'foreignKey' => 'department_id',
        )
);

This gives the relationship between the departments and students tables.

3. Controllers
Each controller has 5 functions. index (like list of students), view (student details), add, edit and delete.
For the url http://localhost/project1/students/view – the view() method in the students controller is executed and at last corresponding views\students\view.ctp view will be rendered.
Understand some lines:

//students index method
$this->set('students', $this->paginate());
//sets pagination

$this->Session->setFlash(__('Invalid student', true));
//sets whatever text in the session and displays in the next page like Invalid data

$this->redirect(array('action' => 'index'));
//redirects to students/index url

$departments = $this->Student->Department->find('list');
$this->set(compact('departments'));
//will set dropdown box of departments in student add

4. Views
Like already said, the corresponding ctp file will be rendered for a method (view method of students controller will render views\students\view.ctp).
The ctp files only have their own content. Other contents like header and footer were rendered for all pages from default.ctp.
All the above code are baked automatically using console, simple and magical.

5. Further
To change the default landing page to students index (http://localhost/project1/ to view list of students) – change the following line in the app\config\routes.php

//Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); - change this to
Router::connect('/', array('controller' => 'students', 'action' => 'index'));

Default layout comes from cake folder. Do not change anything in cake folder. To change the default layout, copy the file from project1\cake\libs\view\layouts\default.ctp to project1\app\views\layouts\. This is the default layout contains header and footer information. Now cake will render the default layout from app folder. Whatever changes making here will take effect in the output.

To develop further refer these:
Core Components
Core Behaviors
Core Helpers

Advertisements
This entry was posted in PHP, Tutorial and tagged , . Bookmark the permalink.

5 Responses to Start Cakephp – How to use shell/console/bake

  1. Frank says:

    i was trying to “bake” but after i chose m for model, it says fatal error Fatal error: Call to undefined function mysql_query() in D:\Program Files\EasyPHP-5.3.3.1\www\cake\libs\model\datasources\dbo\dbo_mysql.php on line 600

    why?

  2. oothet says:

    hi all
    pls help me
    my bake script steps are all smooth but didn’t creat the content of the file except file only , for instance
    controllers for departments table didn’t creat their content ( index(),…… )
    also phpcli.exe has stopped working when I use bake script

  3. Saibal Chkraborty says:

    Boss,
    When deleting department records, related students records stay but those records should hv been removed. pls chk..
    Regards
    saibal

  4. CodeBlood says:

    Its working , thanks buddy.. for simplicity in your articles.. keep it Up.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s