CAKE PHP
INTRODUCTION
How to Install Cakephp
Step 1 : Download the latest version of cakephp from http://cakephp.org/
Step 2 : Extract it and copy the folder in your web root i.e. /var/www/html
Step 3 : Open it in your browser
http://localhost/<installed directory name>
eg:http://localhost/cakephp
Note: You will get warning and notification.
In order to resolve all this, follow this steps.
Step 1 : Change permission for "app/tmp" directory
chmod -R 777 tmp/
Note: If you still get "Your tmp directory is NOT writable." warning , do this
chcon -R -t httpd_sys_content_rw_t 'tmp'
Step 2 : Change the value of 'Security.salt' in app/config/core.php
Configure::write('Security.salt','DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');Change to Configure::write('Security.salt', 'your own 40 alphanumeric characters');
Eg:
Configure::write('Security.salt', 'MyhG9hkrtufgawfuyo75bfveRwernrTi923mfdht');
Note :It's because this salt id comes with the cakephp package,So this will be same for all packages which create major security issues.
Step 3 : change the value of 'Security.cipherSeed' in app/config/core.php to a numeric (digits only) seed value
Configure::write('Security.cipherSeed', '76859309657453542496749683645');
Change to
Configure::write('Security.cipherSeed', 'your own 29 digits');
Eg:
Configure::write('Security.cipherSeed', '59468234159876302050860498265');
Step 4 : Create a Database and Edit the app/config/database.php.default todatabase.php
Step 5 : Change Settings value of database.php file
class DATABASE_CONFIG {var $default = array('driver' => 'mysql','persistent' => false,'host' => 'localhost','login' => 'your_user_name','password' => 'your_password','database' => 'your_database_name','prefix' => '',//'encoding' => 'utf8',);
var $test = array('driver' => 'mysql','persistent' => false,'host' => 'localhost','login' => 'your_user_name','password' => 'your_password','database' => 'your_database_name','prefix' => '',//'encoding' => 'utf8',);}
Eg:
class DATABASE_CONFIG { var $default = array( 'driver' => 'mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'root', 'password' => '', 'database' => 'cake_php', 'prefix' => '', //'encoding' => 'utf8', );
var $test = array( 'driver' => 'mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'root', 'password' => '123456', 'database' => 'cake_php', 'prefix' => '', //'encoding' => 'utf8',);}
Step 6: If you are getting any error related to date then ,
uncomment this line, date_default_timezone_set(''UTC); and change it to your default zone
Eg: date_default_timezone_set('Asia/Kolkata');
Step 7: You have to make changes in the file httpd.conf (/etc/httpd/conf/httpd.conf)
Uncomment LoadModule rewrite_module modules/mod_rewrite.so
And change
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
to
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
As well as in <Directory "/var/www/html"> section
change AllowOverride None to AllowOverride All
Save file and exit
What is Cake PHP :
CakePHP is a free, open-source, rapid development framework in PHP.
CakePHP uses MVC pattern.
Understanding the MVC Pattern :
The MVC (Model View Controller) pattern is a commonly used design pattern
in software development, where the code is separated into three major parts:
models, views, and controllers.
Models
-1) In CakePHP, a model represents a particular database table . Each database table
should have a model representing it. So, in CakePHP, every database table has
its own model.
-2)All PHP code related to accessing, adding, modifying or deleting records from the table are situated
in the model.
-3) Other than that, the model also defines the data validation rules when adding or updating data for
that model. Model can be thought of as the data layer of the application.
-4) The model is also the place where the business logic related to the model should be defined. For
example, if we have a model to represent cars, all actions related to it like buy car, sell car etc. should
be defined in the model.
Models should be the place where the core business logic of an application are defined.
Controllers
Controllers, in CakePHP, control the application flow or logic of the application. Each web request is
directed to a particular controller where the user input (POST or GET data) is accepted. The controller
logic then decides what response is generated. The controller logic normally contains calls to models to
access data, and also other functionalities like access control check etc. Lastly, the controller passes
the response (output) to the view. Controller can be thought as the control logic layer of the application.
As mentioned above, the model should have all the business logic of an application. The controllers
should just delegate the actions to the model, and be light. This design philosophy is sometimes
referred to as the "fat models and thin controllers".
Views
Views are the outputs or responses that are sent back to the user once a request is processed. They
basically consists of markup (like HTML) code with embedded PHP code, but they can also be other
forms of output like XML, PDF document etc. depending on the situation. Views can be thought as the
presentation layer of the application.
Example Application: CakeTooDoo: a Simple To-do List Application
Using CakeTooDoo, we will be able to add new tasks, change the status of a task,
delete a task, and view all the tasks. Specifically, CakeTooDoo will allow us to do the
following things:
1. View all tasks in the list
2. Add a new task to the list
3. Edit a task to change its status
4. View all completed tasks
5. View all pending or not done tasks
6. Delete a task
7. A homepage that will allow access to all the features.
1) Create and configure the database
1. Create a database named caketoodoo in the local machine's MySQL server.
In your favourite MySQL client, execute the following code:
CREATE DATABASE caketoodoo;
2. In our newly created database, create a table named tasks, by running the
following code in your MySQL client:
USE caketoodoo;
CREATE TABLE tasks (
id int(10) unsigned NOT NULL auto_increment,
title varchar(255) NOT NULL,
done tinyint(1ss) default NULL,
created datetime default NULL,
modified datetime default NULL,
PRIMARY KEY (id)
);
NOTE: It is a convention in Cake to have plural words for table names
2) Writing a model
In Cake, each database table should have a corresponding model. The model will be responsible
for accessing and modifying data in the table.
Create a file names Task.php in CakeTooDoo/app/Models directory
<?php
class Task extends AppModel {
var $name = 'Task';
}
?>
NOTE : The file name for a model has to be singular of the corresponding database table name
followed by the .php extension.
Here, the $name is a variable which reperesents the name of the Model.
3) Writing a Controller
Create a file named TasksController.php in CaketooDoo/app/Controller directory
TasksController.php
<?php
class TasksController extends AppController {
var $name = 'Tasks';
}
?>
Each model in the application has a corresponding controller in Cake. So, for our Task model, the
corresponding controller is Tasks Controller.
NOTE : Controller filenames are plural of their model names, and CamelCased
4) Viewing all task in the application
To view a list of all the tasks, we will need to add a function to the Tasks controller, and also add a
view to show us the list of tasks.
Open TasksController.php file and add index() method
<?php
class TasksController extends AppController {
var $name = 'Tasks';
function index() {
$this->set('tasks', $this->Task->find('all'));
}
}
?>
Goto View directory in app and create a directory by name Tasks. All view files related to Controller
are stored in this directory ( Eg: app/View/Tasks/index.ctp)
* View files are stored with extension .ctp which means Cake Template Pages.
Now we create index.ctp file and write a code to display all the tasks.
index.ctp
<h2>Tasks</h2>
<?php if(empty($tasks)): ?>
There are no tasks in this list
<?php else: ?>
<table>
<tr>
<th>Title</th>
<th>Status</th>
<th>Created</th>
<th>Modified</th>
<th>Actions</th>
</tr>
<?php foreach ($tasks as $task): ?>
<tr>
<td>
<?php echo $task['Task']['title'] ?>
</td>
<td>
<?php
if($task['Task']['done']) echo "Done";
else echo "Pending";
?>
</td>
<td>
<?php echo $task['Task']['created'] ?>
</td>
<td>
<?php echo $task['Task']['modified'] ?>
</td>
<td>
<!-- actions on tasks will be added later -->
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
Now,.. open http://localhost/CakeTooDoo/tasks/index in browser. . ..
* Any public functions inside controller classes are called actions.
* The index action, that we just added, handles a request whenever a request is made with the URL
http://localhost/CakeTooDoo/tasks/index.
When a request is made to the index action, the following line is executed:
$this->set('tasks', $this->Task->find('all'));.
This line calls the function find() of the Task model that returns all the tasks stored in the tasks table.
NOTE : find() ---> This function is used to fetch records from the table of the model. By passing
parameters to this function, we can control which records we want to fetch. In the above code,
all was passed to fetch all the records in the task table.
Then, using the set() function of the Tasks controller, it sends this data to the view in an array named
tasks. We can access this array in the view through the $tasks variable.
NOTE : set() ---> function is used to pass data from the controller action to the view. Two parameters
are normally passed to it. The first is the name of the variable that the data will have in the
view, and the second is the actual data that needs to be passed. The set() function is actually
defined in the Controller class that is inherited by AppController, which again is inherited by all
CakePHP controllers.
5) Adding a task
In order to add tasks to our application, we create add() in TasksController.php as
public function add() {
if ($this->request->is('post')) {
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash('The task has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Task not saved. Try Again');
}
}
}
In the same file we add
var $helpers = array('Html', 'Form');
NOTE : Helpers are special modules of CakePHP that provide functions that are commonly
needed in views to format and present data in useful ways. The Form Helper has useful functions
that help in creating HTML forms that can easily show or insert data using a Cake Model.
Now, create add.ctp file in app/View/Tasks directory
<?php echo $this->Form->create('Task');?>
<fieldset>
<legend>Add New Task</legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('done');
?>
</fieldset>
<?php echo $this->Form->end('Add Task');?>
Open index.ctp file to add the links for “List all tasks” and “Add Task”;
<?php echo $this->Html->link('Add Task', array('action'=>'add')); ?>
<?php echo $this->Html->link('List All Tasks', array('action'=>'index')); ?>
open http://localhost/CakeTooDoo/tasks/add to view the Add task.
How it works:
When a request is made to this action, it first checks whether any data has been sent
via the POST method. Any data sent by POST method is automatically stored by
Cake in the array $this->request->data of the controller. If no POST data is present, the add
action does nothing, and the view is rendered showing the empty 'Add Task' form.
When a filled up form is submitted, the submitted data is sent via POST, and stored in
$this->request->data..When this happens, it calls the create() function of the Task model in
the line: $this->Task->create();. The create() function prepares the Task model to add or edit data.
Then, it calls the save() function of the Task model to save the data into our database using the
code: $this->Task->save($this->request->data).
If the data is successfully saved, a success message is stored in the session and the
page is redirected to the index action. The index action shows the newly added task,
along with the success message stored in the session. If for some reason, the data was
not saved in the database, an error message is stored in the session, and the add form
is displayed again along with the error message
6) Editing a Task
Open TasksController.php file and write code for editing the tasks.
public function edit($id = null) {
$this->Task->id = $id;
if ($this->request->is('get')) {
$this->request->data = $this->Task->read();
} else {
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash('Task has been updated.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to update your task.');
}
}
}
Then, you have to create a file named edit.ctp in app/View/Tasks/edit.ctp and write
<?php echo $this->Form->create('Task');?>
<fieldset>
<legend>Edit Task</legend>
<?php
echo $this->Form->hidden('id');
echo $this->Form->input('title');
echo $this->Form->input('done');
?>
</fieldset>
<?php echo $this->Form->end('Save');?>
<?php echo $this->Html->link('List All Tasks', array('action'=>' index')); ?><br />
<?php echo $this->Html->link('Add Task', array('action'=>'add')); ?>
With this a page is created where you can edit your tasks.
To give link to edit.ctp, open index.ctp file and add this line
<?php echo $this->Html->link('Edit', array('action'=>'edit', $task['Task']['id'])); ?>
7) Adding Data Validation
We add data validation for checking empty title.
Validations are done in Model . . So, open Task.php file from app/Models/Task.php
and write
<?php
class Task extends AppModel {
var $name = 'Task';
var $validate = array(
'title' => array(
'rule' => notEmpty,
'message' => 'Title of a task cannot be empty'
)
);
}
?>
8) Deleting a task
To delete a particular task we need to write delete function in our Controller class. So, open TasksController.php file and write the code for delete function
function delete($id=null){
if(!$id){
$this->Session->setFlash('Invalid id for task');
$this->redirect(array('action'=>'index'),null,true);
}
if($this->Task->delete($id)){
$this->Session->setFlash('Deleted task'.$id);
$this->redirect(array('action'=>'index'),null,true);
}
}
To give link to the delete action open index.ctp file and add this line
<?php echo $this->Html->link('Delete', array('action'=>'delete', $task['Task']['id']), null, 'Are you sure you want to delete this task?'); ?>
9) Create Home Page
Open home.ctp file from app/View/Pages directory ,
<h1>Welcome to CakeTooDoo</h1>
<p>CakeTooDoo is a simple but useful application to keep a record
of all the things that you need to do. Using CakeTooDoo,
you can:</p>
<ul>
<li><?php echo $this->Html->link('List all your tasks', array('controller' => 'tasks', 'action'=>'index')); ?></li>
<li><?php echo $this->Html->link('Add new Tasks', array('controller' => 'tasks', 'action'=>'add')); ?></li>
<li>Edit tasks</li>
<li>Delete tasks</li>
</ul>
1. TasksController.php
<?php
class TasksController extends AppController{
var $name = 'Tasks';
var $helpers= array('Html','Form');
function index() {
$this->set('tasks', $this->Task->find('all'));
}
public function add() {
if ($this->request->is('post')) {
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash('The task has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Task not saved. Try Again');
}
}
}
public function edit($id = null) {
$this->Task->id = $id;
if ($this->request->is('get')) {
$this->request->data = $this->Task->read();
} else {
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash('Task has been updated.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to update your task.');
}
}
}
function delete($id=null){
if(!$id){
$this->Session->setFlash('Invalid id for task');
$this->redirect(array('action'=>'index'),null,true);
}
if($this->Task->delete($id)){
$this->Session->setFlash('Deleted task'.$id);
$this->redirect(array('action'=>'index'),null,true);
}
}
}
?>
2. Task.php
<?php
class Task extends AppModel{
var $name = 'Task';
var $validate = array(
'title' => array(
'rule' => 'notEmpty',
'message' => 'Title of a task cannot be empty'
)
);
}
?>
3. index.ctp
<h2>Tasks</h2>
<?php if(empty($tasks)): ?>
There are no tasks in this list
<?php else: ?>
<table>
<tr>
<th>Title</th>
<th>Status</th>
<th>Created</th>
<th>Modified</th>
<th>Actions</th>
</tr>
<?php foreach ($tasks as $task): ?>
<tr>
<td>
<?php echo $task['Task']['title'] ?>
</td>
<td>
<?php
if($task['Task']['done']) echo "Done";
else echo "Pending";
?>
</td>
<td>
<?php echo $task['Task']['created'] ?>
</td>
<td> <?php echo $task['Task']['modified'] ?>
</td>
<td>
<?php echo $this->Html->link('Edit', array('action'=>'edit', $task['Task']['id'])); ?>
| <?php echo $this->Html->link('Delete', array('action'=>'delete', $task['Task']['id']), null, 'Are you sure you want to delete this task?'); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<?php echo $this->Html->link('Add Task', array('action'=>'add')); ?>
<?php echo $this->Html->link('List All Tasks', array('action'=>'index')); ?>
4. add.ctp
<?php echo $this->Form->create('Task');?>
<fieldset>
<legend>Add New Task</legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('done');
?>
</fieldset>
<?php echo $this->Form->end('Add Task');?>
5. edit.ctp
<?php echo $this->Form->create('Task');?>
<fieldset>
<legend>Edit Task</legend>
<?php
echo $this->Form->hidden('id');
echo $this->Form->input('title');
echo $this->Form->input('done');
?>
</fieldset>
<?php echo $this->Form->end('Save');?>
<?php echo $this->Html->link('List All Tasks', array('action'=>' index')); ?><br />
<?php echo $this->Html->link('Add Task', array('action'=>'add')); ?>