CakePHP Model Convention

We have to create the name of Table in the plural form inside the model folder like UsersTable, ArticleCategoriesTable, and UserFavoritePagesTable are all examples of table class names with use of table as a suffix to create a model table.

Entity class names will be used as a singular form at PascalCased format, and it doesn’t use an entity as a suffix. User, ArticleCategory, and UserFavoritePage are all examples of entity names matching with the users, article_categories, and user_favorite_pages tables, respectively.

So, we have to create a database table name and their fields like in given below image.

  1. First point indicates the database name.
  2. Second point indicates the table name as tutorials.
  3. Third point indicates the table fields.
CakePHP Model Convention

Model

Models are the base of the CakePHP application. They allow you to read, update, delete, and select data from the Table. It enables you to establish a relationship between your data, validated data, and applies some rules to build the application. Models create the base for actions and templates file in the controllers.

A model class represents data that can be used for data accessibility in CakePHP applications. They are generally a database table that can be used to access records that manipulates data, such as files, external web services, or iCal events. A model can also linked with other models.

CakePHP’s models contain Table and Entity objects for establishing a connection with the database. In which table objects provide the accessibility from the collection of entities stored in a database. We can create a custom table and stored at src/Model/Table/TutorialsTable.php.:

Example:

Here is the TutorialsTable.php file

  <?php
 namespace App\Model\Table; // it is the package for defining the model in table class.
 use Cake\ORM\Table; //It is object relationship mapper which is used for //converting data into object and vice versa 
 class TutorialsTable extends Table
 { public function initialize(array $config)
  {
  //$this->addBehavior('Timestamp');
  }
 }
 ?> 

Here TutorialsTable is the table name, and we have to used Table as a suffix to  create a table in model folder for accessing the database.

Here we will know about insert, update and delete method using models in CakePHP.

Insert/add Method –

In this method, we will know about the add method, how you can insert or pass the data from the controller to the database. For this operation, you have to create a controller class at src/Controller/ with the name of the TutorialsController.php file.

Here is the example of the Insert method: -

TutorialsController.php

 <?php
 use namespace App\Controller;
 class TutorialsController extends AppController
 {
public function initialize()
{ 
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent for showing a notification
}
public function index()
{
$this->set('tutorials', $this->Tutorials->find('all')); //find function will search all details from //database table name
}
public function add()
{
$row = $this->Tutorials->newEntity(); //newEntity() method is used to create a reserve space //for performing insert method in database table
if ($this->request->is('post')) {
$row = $this->Tutorials->patchEntity($row, $this->request->getData());
if ($this->Tutorials->save($row)) {
$this->Flash->success(_('Your details has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your details.'));
}
$this->set('row', $row);
}
 }
 >? 

In this controller, we have used action as an index method that searches all attributes value, which we have used in the database table.

Now we have to create an index.ctp file in www\my_app_name\src\Template\Tutorials folder, to show the data on to the screen. For this we have to write the following statements.

This is an index.ctp file.

 <h3>ADD Employees </h3><?= $this->Html->link('Add Employee', ['action' => 'add']) ?>
 <table>
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Company</th>
    <th>Email</th>
    <th>City</th>
  </tr>
  <?php foreach ($tutorials as $row): ?> //it will take value one by one from the database table
  <tr>
    <td><?= $row->id ?></td>
            <td><?= $row->name ?></td>
            <td><?= $row->company ?></td>
            <td><?= $row->email ?></td>
            <td><?= $row->city ?></td>
  </tr>
  <?php endforeach; ?>     
 </table> 

The given below image shows that you haven’t passed any values to the database table.

CakePHP Model Convention 1

Now we have to create an add.ctp file in src\Template\Tutorials folder, where we have to write the following statements.

add.ctp

 <h1>Add Details</h1>
 <?php
  echo $this->Form->create($row);
  echo $this->Form->control('name');
  echo $this->Form->control('company');
  echo $this->Form->control('email');
  echo $this->Form->control('city');
  echo $this->Form->button(__('Save'));
  echo $this->Form->end();
 ?> 

When you run this program in localhost by writing http://localhost/my_app_name/tutorials then it will show this output.

CakePHP Model Convention 2

You can see in the above image there is a link of Add Employee. When you click to Add Employee link, then it will show the given below output. After filling your details, click on the Save button, then you redirect to the home page where you can see your details have been added.

And you can also see the records in database table.

CakePHP Model Convention 3

Image:

CakePHP Model Convention 4

Update or Edit Method: - 

In this method, we can update the pre-existing records of the database table. Here we have created an edit method which is define at the TutorialsController.php file.

 <?php
 use namespace App\Controller;
 class TutorialsController extends AppController
 { 
  public function initialize()
  {
  parent::initialize();
  $this->loadComponent('Flash'); // Include the FlashComponent for showing a notification
  }
  public function index()
  {
  $this->set('tutorials', $this->Tutorials->find('all')); //find function will search all details //from database table name 
  }
 public function edit($id = null) // This is an update method
  {
  $row = $this->Tutorials->get($id);
  if ($this->request->is(['post', 'put'])) {
  $this->Tutorials->patchEntity( $row, $this->request->getData() );
  if ($this->Tutorials->save($row)) {
  $this->Flash->success(__('Your Details has been updated.'));
  return $this->redirect(['action' => 'index']);
  }
  $this->Flash->error(__('Unable to update your Details.'));
  }
  $this->set('row', $row);
  }
 } 
 ?> 

In this we have created a link “Update” for calling the edit.ctp file in an index.ctp

<td>
<?= $this->Html->link('Update', ['action' => 'edit', $row->id])
?> </td>

And here we have created an edit.ctp file in \src\Template\Tutorials\ folder.

 <h1>Update Details</h1>
 <?php
  echo $this->Form->create($row);
  echo $this->Form->control('name');
  echo $this->Form->control('company');
  echo $this->Form->control('email');
  echo $this->Form->control('city');
  echo $this->Form->button(__('Save Details'));
  echo $this->Form->end();
 ?> 

Here is the Output:

CakePHP Model Convention 5

After updating the details, we have to again visit at localhost/my_app_name/tutorials then we got this output:

CakePHP Model Convention 6

You can also check in your database like in given below image.

Output:

CakePHP Model Convention 7

Delete method: - 

By using this method, we can delete the records of the database table. Here we have created a delete() method through this we can remove the table records based on the unique id which we have created in our database table. We have to define this method in the TutorialsController.php file. 

 <?php
 use namespace App\Controller;
 class TutorialsController extends AppController
 {
  public function initialize()
  {
    parent::initialize();
    $this->loadComponent('Flash'); // Include the FlashComponent for showing a notification
  }
  public function index()
  {
    $this->set('tutorials', $this->Tutorials->find('all')); //find function will search all details from //database table name
  }
  public function delete($id) // Delete method
  {
  $this->request->allowMethod(['post', 'delete']);
  $row = $this->Tutorials->get($id);
  if ($this->Tutorials->delete($row)) {
    $this->Flash->success(__('Details with id: {0} has been deleted.', h($id)));
    return $this->redirect(['action' => 'index']);
  }
    }
 }
 ?> 

Also, we have to create a delete link in index.ctp file for deleting the record of the table.

 <td><?= $this->Form-> postLink(
        'Delete',
        ['action' => 'delete', $row->id],
        ['confirm' => 'Are you sure?'])
      ?>
 </td> 

Now we have to run our code in localhost like: localhost/my_app_name/tutorials then it will show the given output.

CakePHP Model Convention 8

Similarly, you can check in your database table as the given below image shows.

CakePHP Model Convention 9

Here you can see the record number 20 has been deleted.

Validation in database Fields

The validationDefault() method is used to validate your data fields when the user use a submit or save() method to pass the value in the database. The validation engine of CakePHP is efficient, with several numbers of pre-constructed rules (credit card numbers, email addresses, etc.) and flexibility to add your own validation rules.

We have to define the validation method in the model’s table, then it will validate all those parameters which you have also used in create, delete, and update file.

The name of this class is TutorialsTable.php.  

 <?php
 namespace App\Model\Table;
 use Cake\Validation\Validator;
 use Cake\ORM\Table;
 class TutorialsTable extends Table
 {
 public function initialize(array $config)
 {
  //$this->addBehavior('Timestamp');
 }
 public function validationDefault( Validator $validator )
 {
  $validator
   ->notEmpty( ‘name’ )
   ->requirePresence( ‘name’ )
   ->notEmpty( ‘company ‘)
   ->requirePresence( ‘company’ );
   ->notEmpty( ‘email’ )
   ->requirePresence( ‘email’ )
   ->notEmpty( ‘city’ )
   ->requirePresence( ‘city ‘);       
  return $validator;
 }
 }
 ?> 
CakePHP Model Convention 10

When you have left some textbox then it will show an error message like unable to add details.



ADVERTISEMENT
ADVERTISEMENT