CakePHP 4 Connect Custom Helper To Database Table

Reading Time: 5 minutes
1,684 Views

Inside this article we will see CakePHP 4 connect custom helper to database table. This tutorial contains all basics about connecting a custom helper to database in cakephp application.

Helpers are those functions and methods which helps to complete a specific task of application. In CakePHP there are many default helpers available as Html, URL, Form, etc. To connect a database with user defined helper in cakephp we will use ConnectionManager.

We need custom helper when we want to create some functions which we can re-use through out in the application. Here, we will see the select operation only. But if you need then you can use all other Insert, Update, Delete, etc.

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.

Custom Helper Basic Steps

In CakePHP helpers are provided by class files. There are few basic steps we need to follow to create custom helper:

  • Helper class files should be put inside /src/View/Helper folder.
  • Helper class files should be suffixed with Helper keyword. For Example DataHelper.php.
  • To load helper we use like this $this->loadHelper(‘Data’) and load into AppView.php from /src/View.

Create Custom Helper

We will create a helper which works with string values. Create a file ProductHelper.php file inside /src/View/Helper.

Suppose we have a table products in database. Columns of products table are id, name, email, status. We will select all data from this table using custom helper here.

<?php

namespace App\View\Helper;

use Cake\View\Helper;
use Cake\Datasource\ConnectionManager;

class ProductHelper extends Helper
{
    // List all products
    public function getProductsList($condition = array())
    {
        $db = ConnectionManager::get("default");

        if (!empty($condition)) {

            $results = $db
                ->newQuery()
                ->select('*')
                ->from('products')
                ->where($condition) // [ "id" => 2 ]
                ->execute()
                ->fetch('assoc');
        } else {

            $results = $db
                ->newQuery()
                ->select('*')
                ->from('products')
                ->execute()
                ->fetchAll('assoc');
        }

        return $results;
    }
}

Here, inside this custom helper we have a method to list all products – getProductsList()

Load Helper

By default CakePHP load it’s defined helpers automatically. To load custom helpers we will use AppView.php from /src/View folder.

Open AppView.php and add this line to load helper.

<?php

declare(strict_types=1);

namespace App\View;

use Cake\View\View;

class AppView extends View
{
    public function initialize(): void
    {
        $this->loadHelper("Product"); // Loads ProductHelper.php
    }
}

Now, we will able to use Product helper into template files.

Create Controller & Template

Open project into terminal and run this bake console command.

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

It will create SiteController.php file inside /src/Controller folder. Open file and write this code into it.

<?php

declare(strict_types=1);

namespace App\Controller;

class SiteController extends AppController
{
    public function test()
    {
        //
    }
}

Create a folder called Site inside /templates folder. Create a file with name test.php into /templates/Site folder.

We can use helper and it’s methods into template files.

Custom Helper Usage

Open test.php and try these codes into it.

Get all products

dsadsa
<?php

$products = $this->Product->getProductsList();

echo "<pre>";
print_r($products);

Get a single product

<?php

$products = $this->Product->getProductsList([
    "id" => 2
]);

echo "<pre>";
print_r($products);

We hope this article helped you to learn about CakePHP 4 Connect Custom Helper To Database Table 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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more