Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Sunday, 1 November 2026

CodeIgniter 4 View Cells Explained: Create Reusable View Components with view_cell()

 


CodeIgniter 4 provides a useful feature called `view_cell()` that helps developers create reusable components for their websites. When developing a website, we often need to display the same content or functionality on multiple pages, such as a website header, navigation menu, sidebar, footer, or latest news section. Instead of writing the same HTML and database queries repeatedly, we can use View Cells to create independent components and reuse them wherever required.

A View Cell works through a dedicated Cell class, which is responsible for preparing the data and passing it to a view for display. We can then insert this component into any page using the `view_cell()` function. This approach makes our code cleaner, easier to maintain, and more organized.

In this step-by-step tutorial, we will learn what View Cells are in CodeIgniter 4, how they work, how to create a Cell class, how to connect it with a view, and how to display reusable components on different pages. By the end of this tutorial, you will have a clear understanding of how to use `view_cell()` in your own CodeIgniter 4 projects.


Advantages of View Cells in CodeIgniter 4


CodeIgniter 4 View Cells provide several advantages when developing dynamic websites. They help developers organize their code, avoid repetition, and create reusable components. Understanding these advantages will help you decide when to use View Cells in your projects.

1. Code Reusability


View Cells allow you to create a component once and use it on multiple pages. For example, a website navigation menu or sidebar can be created as a View Cell and reused wherever required.

2. Avoid Code Duplication


Without View Cells, developers may need to write the same HTML and database queries in multiple views. View Cells help eliminate this repetition by keeping common functionality in a single place.

3. Easy Maintenance


When you need to modify a reusable component, you only need to update its Cell class or associated view. The changes can automatically appear wherever that component is used.

4. Separation of Logic and Presentation


View Cells allow you to separate data preparation from HTML presentation. The Cell class handles the required logic, while the view is responsible for displaying the content.

5. Simplified View Files


Using View Cells keeps your main view files clean and organized. Instead of including lengthy HTML or PHP logic, you can simply call the view_cell() function wherever the component is needed.

6. Dynamic Content Display


View Cells can retrieve data from a database or prepare dynamic content before displaying it. For example, you can create a component that displays the latest news, recent posts, or frequently updated information.

7. Improved Code Organization


View Cells help structure your application into smaller, independent components. This makes your CodeIgniter 4 project easier to understand, manage, and extend as it grows.

Conclusion


CodeIgniter 4 View Cells are a convenient way to build reusable and maintainable website components. They reduce code duplication, simplify maintenance, and improve the overall organization of your application. For developers working on dynamic websites, learning view_cell() is a useful step toward writing cleaner and more efficient CodeIgniter 4 code.

I am using an online book-selling website as an example. In this application, book categories are loaded through a View Cell and automatically displayed on every page because they are used in the navigation menu.

Using a View Cell eliminates the need to fetch book categories separately in every page controller. This reduces code duplication, simplifies controller logic, and makes the application easier to maintain.

Step 1

Create a folder Cells in app folder and create a file BookCategoryMenu.php. This file fetch category records from database and send to view bookcategorymenu.php 

<?php

namespace App\Cells;


use Config\Database;

class BookCategoryMenu
{
    public function getCategories(): string
    {
        $db = Database::connect();

        $categories = $db->table('bookcategory')
            ->select('ID, CatName')
            ->where('RStatus', 1)
            ->orderBy('CatName', 'ASC')
            ->get()
            ->getResultArray();

        return view('shared/bookcategorymenu', [
            'categories' => $categories
        ]);
    }
}


Step 2 : 

bookcategorymenu.php wrap caregory into html coming from BookCategoryMenu.php from app/Cells folder. You can change html as per the your code base.


<li class="g-has-sub">
    <a href="#showcase" class="g-link">Category <i class="g-caret"></i></a>
    <ul class="g-sub">
        <?php foreach (($categories ?? []) as $category): ?>
            <li>
                <a href="<?= site_url('category/' . $category['ID'] . '/' . esc($category['CatName']) ) ?>">
                    <?= esc($category['CatName']) ?>
                </a>
            </li>
        <?php endforeach; ?>

    </ul>
</li>

Step 3 :

Finaly use this html into menu.php file and render it to main website menu

 <?= view_cell('App\Cells\BookCategoryMenu::getCategories') ?>

Tuesday, 29 September 2026

How to Build a Secure Login System in CodeIgniter (Step-by-Step Tutorial)

 


Are you looking to build a secure user authentication system for your web application? In this comprehensive, step-by-step tutorial, you will learn how to implement a complete login and authentication system using CodeIgniter. Whether you are building a new project from scratch or enhancing an existing application, this guide walks you through setting up controllers, configuring database models, managing user sessions, and validating credentials securely so you can protect your app against unauthorized access.

Monday, 9 February 2026

Complete Blog System in CodeIgniter 4.5.0 with Source Code (Free Download)

 




Are you looking for a powerful and ready-to-use blog system built with CodeIgniter 4.5.0? I have developed a complete, production-ready blog web application that includes all essential blogging features with optimized performance and smart image handling.

This project is designed for developers, students, and learners who want to understand real-world blog development using CodeIgniter or build their own blogging platform quickly.

Wednesday, 14 September 2022

File Upload with new name Codeigniter

 HTML

<form method="post"  action="<?php echo site_url('/Admin/newsadddb'); ?>" enctype="multipart/form-data">

 <input type="file" name="NewsFile" id="NewsFile" style="display:none">

<input type="submit" name="submit" value="Save" class="btn btn-danger" >

</form>

Monday, 11 July 2022

Google Recaptcha Integration | PHP , ASP.NET C# , Codeiginater 4

 




Wednesday, 29 June 2022

Unable to write in session folder in windows 10 using Codeigniter 4

 This post is applied on following Codeigniter Error

  • Unable to write in session folder in windows 10 using Codeigniter 4
  •  SYSTEMPATH\Session\Handlers\FileHandler.php at line 102
  •  Uncaught Exception: Session: Configured save path
  • CodeIgniter\Session\Exceptions\SessionException

Solution 

I solved this issue... for anyone experiencing this... changing permissions to anything didn't work. Somehow they had been corrupted on the actual folder so I deleted the cache folder and session folder and created new folders and replaced the contents (files ended up not being an issue). This fixed my issue.

Note: In my case, this error occurred due to google cloud backup because I was working simultaneously while the backup is running and Google Backup corrupted the session folder. 

Friday, 8 April 2022

Send Whatapp message from contact form | PHP

 

PHP Code

<?php

if(isset($_POST['submit']))
{

 

$str="https://wa.me/+91-9795000000?text=";

$str.="Roll%20:%20" . preg_replace('/ /','%20',$_POST['Roll']);

$str.= ",Name%20:%20" . preg_replace('/ /','%20',$_POST['Name']);

$str.=",City%20:%20" . preg_replace('/ /','%20',$_POST['City']);

header("Location: $str");
}

?>          


HTML

<form method="post" style="margin:4%">

 

    <input type="text" name="Roll" /><br />

    <input type="text" name="Name" /><br />

    <input type="text" name="City" /><br />

    <input type="submit" name="submit" value="Send" />

 

</form>


Tuesday, 15 March 2022

Layout In CI

Step 1 :

Make a folder named shared in app/Views

Step 2 : 

Make 3 files named menu.php,footer.php,layout.php

menu.php : will hold menu of website

layout.php : will hold master layout page for your website

footer.php : will hold footer code 

Thursday, 10 February 2022

Begin CodeIgniter 4.1.8

Whoops! We seem to have hit a snag. Please try again later

Solution : 


Your PHP is missing intl extension. It is useful for formatting currency, number and date/time as well as UCA-conformant collations, for message formatting and normalizing text..etc.


Follow the steps to install it in XAMPP -

  • Open [xampp_folder_path]/php/php.ini to edit.
  • Search for ;extension=intl and remove the ;.
  • Save the php.ini file and restart Apache.

Sunday, 14 November 2021

Layout/Master page in laravel

Layout/Master page in laravel

Making Layout or Master page in laravel is very simple . Go through the given steps below.

Step 1: Make a view named Layout.blade.php

Make a view for layout named layout.blade,php in resources\views folder.

Friday, 12 November 2021

User difined function Laravel

 We make user difined function to reuse code. To use user difined function you need to follow the steps
given below.

  • Make your file in app folder and write your code in that file . In my case file name is helper.php and funtion name is Title . i.e.
function Title()
{
   echo "Girfa IT Services";
}
  • Goto  composer.json file and add the following lines in autoload section.In my case pagelib.php is my file. Write your file name.
        "autoload": 
        {
        "files" :["app/pagelib.php"],
        },
  • Now you can call the function inside of helper.php  file , anywhere in your project.
Note : Run given command  for update your function

          composer dump-autoload 

Then, in your hosting site, you can update two files, autoload_classmap.php and autoload_static.php, manually in vendor/composer folder. I prefer to copy and paste the added classes from local to the hosting server

Save form data into database

 This post will help  step by step to understand , how to save your HTML form data into Mysql Database.

Database Table structure 


Form

Step 1

Make  HTML Form , code is given below

<form method="post" action="index">

    @csrf

    Name : <input type="text" name="name" placeholder="Your Name" required class="form-control"><br>

    Phone : <input type="text" name="phone" required placeholder="Phone Number" class="form-control"><br>

    Message :

    <textarea rows="5" name="message" required placeholder="Message" class="form-control"></textarea><br>

    <input type="submit" value="Save" name="submit">

</form>


Step 2 


Create Model by given command

php artisan make:model stumodel 

Model Location :  app\Models

Model Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class stumodel extends Model
{
protected $table = 'kashiquery';
    use HasFactory;
public $timestamps=false;
protected $fillable = [
'name', 'phone','message','createddate'
];
}

Step 3 : Create Controller


Create controller by given command below

Command : PHP artisan make:controller common

Controller location : app\Http\Controllers

Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\stumodel;
class common extends Controller
{
    public function AddData(Request $req)
{
        $data=new stumodel;
//$r = $req->input();
$data->name=$req["name"];
$data->phone=$req["phone"];
$data->message=$req["message"];
$data->createddate=date("Y-m-d");
$data->save();
return redirect('index');
    }
}
 

Step 4 : Configure Route


Route File Location : \routes\web.php 

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\common;


Route::get('/', function () {
    return view('index');
});
Route::view('index','index');
Route::post('index',[common::class,'AddData']);





Friday, 29 October 2021

Laravel command for beginners

 

Create and run project using composer

composer create-project laravel/laravel your-project-name

cd your-project-name

Goto project folder i.e your-project-name

php artisan serve

Next Topic

Thursday, 22 April 2021

PHP 404 page handling

 

PHP 404 page handling

Server shows 404 error code when requested resource not found at server. By default, the browser display 404 error page .which is not as user-friendly because it does not show our website look and layout. if you want to custom 404-page handling page then this post will help you. to do the above let follows the steps given below.