Hello Reader's ,
Hope your are doing good today.
After working on CURD in cakephp 2.x+ version ,today i am going to update you with Cakephp 3.0 CURD example.
Some directory changes made in cakephp 3.0 you can read here http://book.cakephp.org/3.0/en/intro/cakephp-folder-structure.html
Now let's start CURD with Cakephp 3.0.
Step 1:
First you need to create a database & tables.
CREATE DATABASE `blog`;
USE `blog`;
#Table :-articles
CREATE TABLE `articles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) DEFAULT NULL,
`body` text,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
Step 2: Configure your database.
Location : config/app.php
Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
'username' => 'root', // your mysql user name
'password' => 'root', //your mysql password
'database' => 'blog', // databse name
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
]
Step 3: Now create our model, view and controller for our CRUD application.
Model: go to your project folder and create ArticlesTable "src/Model/Table/ArticlesTable.php"
// Naming conventions are very important in CakePHP. By naming our Table object ArticlesTable, CakePHP can automatically infer that this Table object will be used in the ArticlesController, and will be tied to a database table called articles.
namespace App\Model\Table;
use Cake\ORM\Table;
class ArticlesTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp'); //It will help to store created datetime in db
}
}
Controller:
go to your project folder and create ArticlesController "src/Controller/ArticlesController.php"
<?php
namespace App\Controller;
class ArticlesController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent
}
public function index()
{
$this->layout = false;
$this->set('articles', $this->Articles->find('all'));
}
// View Atricles details function
public function view($id = null)
{
$this->layout = false;
$articles = $this->Articles->get($id);
$this->set(compact('articles'));
}
//Add articles
public function add()
{
$this->layout = false;
$article = $this->Articles->newEntity();
//Entity is a set of one record of table and their relational table, on that you can perform operation without touch of database and encapsulate property of entity (fields of table) as you want.
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your article.'));
}
$this->set('article', $article);
}
//Edit articles
public function edit($id = null)
{
$this->layout = false;
$article = $this->Articles->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your article.'));
}
$this->set('article', $article);
}
//Delete articles
public function delete($id)
{
$this->request->allowMethod(['post', 'delete']);
$article = $this->Articles->get($id);
if ($this->Articles->delete($article)) {
$this->Flash->success(__('The article with id: {0} has been deleted.', h($id)));
return $this->redirect(['action' => 'index']);
}
}
}
View: Contain .ctp files, which will display our view files.
Location: "src/Template/Articles/index.ctp"
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table border="1" align="center">
<tr >
<th colspan="4"><h1>Blog Articles</h1></br>
<p><?= $this->Html->link("Add New Article", ['controller'=>'Articles','action' => 'add']) ?></p></br></br>
<span style="color:red"><?= $this->Flash->render('flash') ?></span></br>
</th>
</tr>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
<th>Action</th>
</tr>
<!-- Here is where we iterate through our $articles query object, printing out article info -->
<?php foreach ($articles as $article): ?>
<tr>
<td><?= $article->id ?></td>
<td>
<?= $this->Html->link($article->title, ['controller' => 'Articles','action' => 'view', $article->id]) ?>
</td>
<td>
<?= $article->created->format(DATE_RFC850) ?>
</td>
<td>
<?= $this->Html->link('Edit', ['action' => 'edit', $article->id]) ?>
<?= $this->Form->postLink(
'Delete',
['action' => 'delete', $article->id],
['confirm' => 'Are you sure?'])
?>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
add.ctp
Location: "src/Template/Articles/add.ctp"
<h1>Add Article</h1>
<?php
echo $this->Form->create($article);
echo $this->Form->input('title');
echo $this->Form->input('body', ['rows' => '4']);
echo $this->Form->button(__('Save Article'));
echo $this->Form->end();
?>
view.ctp
Location: "src/Template/Articles/view.ctp"
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table border="1" align="center">
<tr >
<th colspan="3"><h1>Blog Articles Details</h1></th>
</tr>
<tr>
<th>Title</th>
<th>Body</th>
<th>Created</th>
</tr>
<tr>
<td><?= h($article->title) ?></td>
<td>
<?= h($article->body) ?>
</td>
<td>
<?= $article->created->format(DATE_RFC850) ?>
</td>
</tr>
<tr>
<td colspan="3" align="center"> <?= $this->Html->link('Back', ['controller' => 'Articles','action' => 'index']) ?></td>
</tr>
</table>
</body>
edit.ctp
Location: "src/Template/Articles/edit.ctp"
<h1>Edit Article</h1>
<?php
echo $this->Form->create($article);
echo $this->Form->input('title');
echo $this->Form->input('body', ['rows' => '3']);
echo $this->Form->button(__('Save Article'));
echo $this->Form->end();
?>
Please feel free to give us your feedback in comments.
3 Comment(s)