CakePHP 4 What is Mutator & Why Application Uses?

Share this Article
Reading Time: 6 minutes
266 Views

Inside this article we will understand the concept of CakePHP 4 what is mutator and why application uses it. This tutorial contains a classified information about using mutator in a cakephp application.

Mutator means something we want to save into database but in between we manipulate data. Basically it is the process where we do the data manipulation in the intermediate state after form submission and before save to database. We can alter data before saving into database table.

Suppose we have a table called products into database. Table products have these columns – ( id, name, cost, description, seller_email, status ). We will make few mutators for these –

  • Convert name value to uppercase before save to database table.
  • Replace gmail.com to example.net from email value before saving to database.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE mydatabase;

Successfully, we have created a database.

Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –

//...

'Datasources' => [
        'default' => [
            'host' => 'localhost',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',

            'username' => 'root',
            'password' => 'sample@123',

            'database' => 'mydatabase',
            /*
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
             */
            //'schema' => 'myapp',

            /*
             * You can use a DSN string to set the entire configuration
             */
            'url' => env('DATABASE_URL', null),
        ],
  
     //...

//...

You can pass host, username, password and database.

Successfully, you are now connected with the database.

Create Model & Entity

Open project into terminal and run this bake console command –

$ bin/cake bake model Products --no-rules --no-validation

It will create several files like Model, Entity, Test & Fixture.

Model class file ProductsTable.php is inside /src/Model/Table folder. Entity class file Product.php is inside /src/Model/Entity folder.

Code for Model class file.

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class ProductsTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('products');
        $this->setPrimaryKey('id');
    }
}

Code for Entity class file. We will define the mutator methods into this entity class. We will manipulate data at runtime before saving to database table.

Mutator methods will be prefixed with _set and then column name in camel cased.

For example for name column it will be _setName(), seller_email column as _setSellerEmail()

<?php

declare(strict_types=1);

namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * Product Entity
 *
 * @property int $id
 */
class Product extends Entity
{
    protected $_accessible = [
        'name' => true,
        'cost' => true,
        'seller_email' => true,
        'description' => true,
        'status' => true,
    ];

    public function _setName($value)
    {
        // It will convert value to uppsercase
        return strtoupper($value);
    }

    public function _setSellerEmail($value)
    {
        // It will replace gmail.com to example.net from value
        return str_replace("gmail.com", "example.net", $value);
    }
}

Mutator Method for Name

public function _setName($value)
{
    // It will convert value to uppsercase
    return strtoupper($value);
}

Mutator Method for Email

public function _setSellerEmail($value)
{
    // It will replace gmail.com to example.net from value
    return str_replace("gmail.com", "example.net", $value);
}

Create Controller

To create controller we will use bake console command –

$ bin/cake bake controller Sites --no-actions

It will create a file SitesController.php inside /src/Controller folder.

<?php

declare(strict_types=1);

namespace App\Controller;

class SitesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        $this->loadModel("Products");
        $this->autoRender = false;
    }

    public function saveProduct()
    {
        $productEntity = $this->Products->newEmptyEntity();

        $data = [
            "name" => "Product 1", // before save name will be "PRODUCT 1"
            "cost" => 500,
            "seller_email" => "seller@gmail.com", // before save seller_email will be "seller@example.net"
            "description" => "Sample content",
            "status" => 1
        ];

        $productEntity = $this->Products->patchEntity($productEntity, $data);

        $this->Products->save($productEntity);
    }
}

Create Route

Open routes.php from /config folder and add this route into it.

//...

// Product Route
$routes->connect(
   '/save-product',
   ['controller' => 'Sites', 'action' => 'saveProduct']
);
//...

Application Testing

Open project into terminal and run this bake console command to start development server.

$ bin/cake server

URL: http://localhost:8765/save-product

You should see manipulated values will be saved into database table.

We hope this article helped you to learn about CakePHP 4 What is Mutator & Why Application Uses Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5