« Previous | Next»

CakePHP: Baking a Application in Minutes

Posted by coldtobi | 20 Mar, 2011, 12:17

On my last PHP project I spent too much time on basic tasks like form validation, generation and all the stuff behind. As this "problems" are quite common this is basically a reinvention of the wheel. So I started looking for a good, easy to understand PHP Framework to speed things up. 

What I found is CakePHP, a MVC based framework.

Ok, there are several frameworks available, so why to choose CakePHP? I think this is up to personal taste which framework appeals you most. Of course, there are comparisons in the blogosphere, so this can be a starting point for the decision. (for example)

Back to the cake. Well, IMPRESSIVE. This framework saves you lots of work -- most functions you need everyday are already there and the documentation called "Cookbook" is also quite complete and easy to understand. The API is not very complicated, so learning this framework is definitely faster than writing your own framework. (For the German readers: read this article).

Nevertheless, back to the topic again.  

To get an application up and running in minutes you can use a method they call scaffolding. You setup a scaffold* and your are ready.

(* Your scafold consists of a database and two files.... Of course, I assume you have your webserver and database server ready, and for the sake of easiness debian running to install all required packages. As an alternative to a webserver, you might want to check the package cakephp-instaweb and the docs here. Also for the sake of easiness, this tutorial shows will not use mod_rewrite, to avoid the hassle involving proper mod_rewrite configuration)

Don't believe it?

Try it yourself. 

_ASIP_

OK Lets do a TODO-List? Start your stopwatch....

1) Install cakephp

aptitude install cakephp cakephp-scripts

2)  "bake" your application in /var/www as the webserver user (just answer cake's questions as below. Most are default, so just press "enter". I marked all where you indeed have to enter something red.)

#su
Password:
#su www-data
#cake bake todo

Welcome to CakePHP v1.3.7 Console
---------------------------------------------------------------
App : www
Path: /var/www
---------------------------------------------------------------
Bake Project
Skel Directory: /usr/share/php/cake/console/templates/skel
Will be copied to: /var/www/todo
---------------------------------------------------------------
Look okay? (y/n/q)
[y] >
Do you want verbose output? (y/n)
[n] >
---------------------------------------------------------------
Created: todo in /var/www/todo
---------------------------------------------------------------

Creating file /var/www/todo/views/pages/home.ctp
Wrote `/var/www/todo/views/pages/home.ctp`
Welcome page created
Random hash key created for 'Security.salt'
Random seed created for 'Security.cipherSeed'
CAKE_CORE_INCLUDE_PATH set to /usr/share/php in webroot/index.php
CAKE_CORE_INCLUDE_PATH set to /usr/share/php in webroot/test.php
Remember to check these value after moving to production server
Your database configuration was not found. Take a moment to create one.
---------------------------------------------------------------
Database Configuration:
---------------------------------------------------------------
Name: 
[default] >
Driver: (db2/firebird/mssql/mysql/mysqli/odbc/oracle/postgres/sqlite/sybase)
[mysql] > sqlite
Persistent Connection? (y/n)
[n] >
Database Host: 

[localhost] >
Port? 
[n] >
User: 
[root] >
Password: 
>
The password you supplied was empty. Use an empty password? (y/n)
[n] > y
Database Name: 
[cake] > /var/www/todo/db.sqlite
Table Prefix? 
[n] >
Table encoding? 
[n] >

---------------------------------------------------------------
The following database configuration will be created:
---------------------------------------------------------------
Name:         default
Driver:       sqlite
Persistent:   false
Host:         /var/www/todo/db.sqlite
User:         root
Pass:        
Database:     todo
Look okay? (y/n)
[y] >    
Do you wish to add another database configuration? 
[n] >
#

3) populate your database 

Our todo should have a datestamp when modified, a prioriy, a progress indicator, a checkbox if its done,  some title and a description ....

  #(copy the following to a file name,  for example to  /tmp/db.txt)

CREATE TABLE todos (
  id INTEGER AUTO_INCREMENT,
  modified datetime ,
  title varchar(127) ,
  description text ,
  done tinyint(1) DEFAULT 0,
  priority int(11) ,
  progress integer ,
  PRIMARY KEY (id)
);

  ... and ask sqlite to initialize it by

sqlite /var/www/todo/db.sqlite </tmp/db.txt

 

4) Disable mod_rewrite setting in  /var/www/todo/config/core.php, by remove the comment in around line 69:

 /**
 * To configure CakePHP *not* to use mod_rewrite and to
 * use CakePHP pretty URLs, remove these .htaccess
 * files:
 *
 * /.htaccess
 * /app/.htaccess
 * /app/webroot/.htaccess
 *
 * And uncomment the App.baseUrl below:
 */
   
     Configure::write('App.baseUrl', env('SCRIPT_NAME'));

 

5)  Create the Controller for your todo list: (create the file  /var/www/todo/controllers/todos_controller.php)

Containing just those few lines:

<?php

class TodosController extends AppController {
                var $scaffold;
}
?>

6) Create the Model for your todo list (create the file /var/www/todo/models/todo.php)

  With this:

<?php

class Todo extends AppModel {
        var $name = 'Todo';

?>

7) Enjoy

Point your browser to  http://localhost/todo/index.php/todos for your todo list, a nice scarford CRUD application

 

A) Bonus points:

For bonus points and to demonstrate the power of CakePHP, lets add validation and some basic sorts to the ToDo List. I want to sort it regarding priority and put the "dones" at the end of the list: Just Change  /var/www/todo/models/todo.php to the following:

 <?php

class Todo extends AppModel {
        var $name = 'Todo';

        var $validate = array(
                'title' => array(
                        'rule' => 'notEmpty',
                        'message' => "Bitte ausfüllen"),
                'priority' => array(
                        'rule' => 'notEmpty',
                        'message' => "Bitte ausfüllen"),
                'description' => array(
                        'rule' => 'notEmpty',
                        'message' => "Bitte ausfüllen"),

        );

        function beforeFind($query) {
                $query['order'][]        = 'done';
                $query['order'][]        = 'priority DESC';
                return $query;
        }

}
?>

 

Ok, there we are. Pencils down.

So, what does your stop watch show?  IMPRESSIVE, right?

 _ASIP_

A Word of WARNING:

Note that this is fine for private purposes, but never put this online. For example, the scafolding code will not care about XSS!

For example, enter a todo with this text: <script type="text/javascript">alert("XSS");</script>

REPEAT: IT IS NOT SAFE TO USE A SCAFOLDED APPLICATION. CAKE EXPLICITLY TELLS THAT YOU MUST SANIZITE ALL DATA BY YOURSELF! 

 

Blog and Website | Comments (0) | Trackbacks (0)

Related Articles:

0 Comments | "CakePHP: Baking a Application in Minutes" »