CakePHP is an open source PHP framework built around Model-View-Controller (MVC). We will begin to create a small application that will do some basic Create, Read, Update, Delete (CRUD) operations on our database.
- Model: It manages the data. It stores into and retrieves from the database.
- View: It is for the presentation and is responsible for displaying the data provided by the model in a specific format.
- Controller: Handles the model and view layers to work together.
View, add, edit and delete functionality. You can download the full tutorial here.
Step1: The Database Structure
To create a database and table:
- CREATE TABLE IF NOT EXISTS `demomovies` (
-
- `id` char(36) NOT NULL,
-
- `title` varchar(255) DEFAULT NULL,
-
- `genre` varchar(45) DEFAULT NULL,
-
- `rating` varchar(45) DEFAULT NULL,
-
- `format` varchar(45) DEFAULT NULL,
-
- `length` varchar(45) DEFAULT NULL,
-
- `created` datetime DEFAULT NULL,
-
- `modified` datetime DEFAULT NULL,
-
- PRIMARY KEY (`id`)
-
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
- INSERT INTO `demomovies` (`id`, `title`, `genre`, `rating`, `format`, `length`, `created`, `modified`) VALUES
-
- ('54d9874c-ae74-4451-b54a-14f01bafaffa', 'secondfirst', 'sdfsd', '4.5', 'sdf', 'sdf', '2015-02-10 05:21:32', '2015-02-10 05:34:01'),
-
- ('54d98aa7-d65c-40cd-8b7f-14f01bafaffa', 'second', 'firest', '5.4', 'dsf', 'sadf', '2015-02-10 05:35:51', '2015-02-10 05:35:51');
Step 2: Create Model, Controller and View
Create a demomovie.php file and save it in the following path.
C:\xampp\htdocs\cakephp_example\app\Model
Open the demomovie.php file.
- <?php
- class Demomovie extends AppModel {
-
- var $name = 'demomovie';
-
- var $validate =array(
-
- 'title' =>array(
-
- 'alphaNumeric' =>array(
-
- 'rule' => array('minLength',2),
-
- 'required' => true,
-
- 'message' => 'Enter should be minimum 2 only')
-
- ),
-
- 'genre' =>array(
-
- 'alphaNumeric' =>array(
-
- 'rule' => array('minLength',4),
-
- 'required' => true,
-
- 'message' => 'Enter should be minimum 4 only')
-
- ),
-
- 'rating' =>array(
-
- 'alphaNumeric' =>array(
-
- 'rule' => array('minLength',2),
-
- 'required' => true,
-
- 'message' => 'Enter should be minimum 4 only')
-
- )
-
- );
-
- }
-
- ?>
-
Save it.
Controller
Create DemomoviesController.php and save it in the following path.
C:\xampp\htdocs\cakephp_example\app\Controller
Open DemomoviesController.php files and paste in the following code.
View
Create a Demomovies folder.
C:\xampp\htdocs\cakephp_example\app\View
Create add.ctp , edit.ctp , index.ctp , view.ctp files
C:\xampp\htdocs\cakephp_example\app\View\Demomovies
Set route
Open routes.php with the following pat.
- Router::connect('/', array('controller' => 'demomovies', 'action' => 'index', 'home'));
Save it.
The following are screen shots of view, add, edit, and delete.
View
Add
Edit
After edit form: