Inside this article we will understand the concept of CakePHP 4 what is accessor and why application uses it. This tutorial contains a classified information about using accessor in a cakephp application.
Accessor means something we want to access from application. Basically it is the process where we do the data manipulation in the intermediate state when we access data from application. We can alter data after getting from database and before outputting it to the user interface.
Application uses to make data in some format which suits to the end user. Sometimes we save data in raw format to the database. Display a raw format data is not a good practise. Here we can use the concept of accessor to convert data from raw format to a structures format.
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 accessors for these –
- Convert name value to uppercase before output
- Replace gmail.com to example.net from email value before output
Learn More –
- CakePHP 4 How To Create Custom Helper Tutorial
- CakePHP 4 How To Create Custom Layout Tutorial
- CakePHP 4 Connect Custom Helper To Database Table
- CakePHP 4 Database Operations Using ConnectionManager
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 accessor methods into this entity class. We will manipulate data at runtime before outputting to end users.
Accessor methods will be prefixed with _get and then column name in camel cased.
For example for name column it will be _getName(), seller_email column as _getSellerEmail()
<?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 _getName($value) { // It will convert value to uppsercase return strtoupper($value); } public function _getSellerEmail($value) { // It will replace gmail.com to example.net from value return str_replace("gmail.com", "example.net", $value); } }
Accessor Method for Name
public function _getName($value)
{
// It will convert value to uppsercase
return strtoupper($value);
}
Accessor Method for Email
public function _getSellerEmail($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 loadProducts() { $products = $this->Products->find()->toList(); if (count($products) > 0) { foreach ($products as $product) { // Automatically accessors will be used for these columns when we access echo "Name: " . $product->name . " and Seller email: " . $product->seller_email . "<br/>"; } } } }
Create Route
Open routes.php from /config folder and add this route into it.
//... // Product Route $routes->connect( '/products', ['controller' => 'Sites', 'action' => 'loadProducts'] ); //...
Application Testing
Open project into terminal and run this bake console command to start development server.
$ bin/cake server
URL: http://localhost:8765/products
We hope this article helped you to learn about CakePHP 4 What is Accessor & Why Application Uses Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
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.