Show Menu
Cheatography

CodeIgniter4 for Beginners Cheat Sheet (DRAFT) by

CodeIgniter 4 is a modern, fast, lightweight, PHP MVC framework that allows you to build secure applications quickly and easily.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

TOPIC 1: GETTING STARTED

 

1.1. Instal­lat­ion

Download Composer
 
Using Composer
 
composer create­-pr­oject codeig­nit­er4­/ap­pst­arter yourap­pname

1.2. Prepare Running Your App

Configure CI4 to display error messages
Root|env
 
Change
env
to
.env
Root|.env
 
# ENVIRO­NMENT

CI_ENV­IRO­NMENT = develo­pment
Hosting with Apache
Virtual Hosting
Step 1: In xamp|a­pac­he|­con­f|h­ttp­d.conf
 
# Virtual hosts

Include conf/e­xtr­a/h­ttp­d-v­hos­ts.conf
Step 2: xamp|a­pac­he|­con­f|e­xtr­a|h­ttp­d-v­hos­ts.conf
 
 <Vi­rtu­alHost *:80> 
ServerName yourappname.local
Docume­ntRoot "D:/xampp/htdocs/yourappname/public"
<Di­rectory "D:/xampp/htdocs/yourappname/public">
Options Indexes FollowSymLinks
AllowO­verride All
Require all granted
</Directory>
</VirtualHost>
Step 3: Edit the hosts file
The hosts file is used to map domain names to IP addresses. You can find this file at
C:\Win­dow­s\S­yst­em3­2\d­riv­ers­\et­c\hosts
(on Windows) or /etc/hosts (on Linux or macOS). Add the following line to the hosts file:
 
127.0.0.1 yourap­pna­me.l­ocal
Finally
 
Restart Apache in the XAMPP control panel.
Remove public­/in­dex.php/ from URL
Step 1: Change the
App.php
file
 
Open
projec­t_n­ame­/ap­p/C­onf­ig/­App.php*


changes are as follows:
public $baseURL = 'http:­//l­oca­lho­st:­8080';

to
public $baseURL = 'http:­//l­oca­lho­st/­you­r_p­roj­ect­_na­me/';
 
And the second change in the
app.php
file:
public $uriPr­otocol = 'REQUE­ST_­URI';

to
public $uriPr­otocol = 'PATH_­INFO';
Step 2: Copy
index.php
and
.htaccess
 
Go to
public directory

Copy
index.php
and
.htaccess

To
codeigniter app root directory
Step 3: Change the
index.php
 
In the root project directory, open
index.php
and edit the following line:
$pathsPath = FCPATH . '../ap­p/C­onf­ig/­Pat­hs.p­hp';

change TO
$pathsPath = FCPATH . 'app/C­onf­ig/­Pat­hs.p­hp';

If the above solution is not work for; so you can configure your apache server; as shown below:
In the apache server, the mode rewrite is already on. But some default values need to be changed on
/etc/a­pac­he2­/ap­ach­e2.conf
file. Following are changes,
First, find

<Di­rectory /var/www/>
Options Indexes FollowSymLinks
AllowO­verride None
Require all granted
</D­ire­cto­ry>

And change
AllowO­verride
None to
All
and save.
Then enable mode rewrite
Then restart the server,

1.3. Run the applic­ation in a browser

Local Develo­pment Server
php spark serve
Virtual Hosting
Removing the index.php
http:­­//l­­oc­a­l­ho­­st/­­yo­u­r­_p­­roj­­ec­t­_­na­me/

TOPIC 2: VIEW LAYOUTS

 
How to integrate an admin layout into CodeIg­niter 4 so that it is separate from the public layout.

2.1. Create a folder for admin layout

In the
app/Views
folder,
Create a new folder named
admin
to hold the layout files for the admin page.
For example:
app/Vi­ews­/ad­min­/la­you­t.php
.

2.2. Create a layout file for the admin page

<!-- 
app/Vi­ews­/ad­min­/la­you­t.php

In the admin folder, create a generic layout file for your admin page. 
For example: app/Views/admin/layout.php. 
In this file, you can define layout elements such as header, menu, footer, 
and content. 

For example:
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Layout</title>
</head>
<body>
    <header>
        <h1>Admin Header</h1>
    </header>
    <nav>
        <ul>
            <li><a href="#">Dashboard</a></li>
            <li><a href="#">Users</a></li>
            <li><a href="#">Settings</a></li>
        </ul>
    </nav>
    <main>
        <?php echo $this->renderSection('content') ?>
    </main>
    <footer>
        <p>Admin Footer</p>
    </footer>
</body>
</html>

2.3. Create view files for each admin page

app\Vi­ews­\ad­min­\da­shb­oar­d.php
 <?php $this-­>ex­ten­d('­adm­in/­lay­out') ?> 

<?php $this-­>se­cti­on(­'co­ntent') ?>
<h2>Dashboard</h2>
<p>­Welcome to the admin dashboard!</p>
<?php $this-­>en­dSe­ction() ?>

2.4. Create routes for admin page

app/Co­nfi­g/R­out­es.php
 $route­s->­gro­up(­'ad­min', 
['name­space' => 'App\C­ont­rol­ler­s\A­dmin'],
functi­on(­$ro­utes) {
$route­s->­get­('d­ash­board', 'Dashboard::index');
$route­s->­get­('u­sers', 'Users::index');
$route­s->­get­('s­ett­ings', 'Settings::index');
});
Here, all routes for the admin page start with the prefix admin, and all the contro­llers for the admin page are located in the App\Co­ntr­oll­ers­\Admin namespace.

2.5. Create contro­llers for the admin page

app\Co­ntr­oll­ers­\Ad­min­\Da­shb­oar­d.php
 <?php 
namespace App\Controllers\Admin;
use CodeIgniter\Controller;

class Dashboard extends Controller
{
public function index()
{
return view('admin/dashboard');
}
}
In each of these controller files, you need to inherit from CodeIg­nit­er­\Con­troller and define a method to display the corres­ponding page. In this method, you can use the view helper to display the file view corres­ponding to that page.
 

TOPIC 1: NAMING CONVENTION

 

Controller file and class

File:
UsersC­ont­rol­ler.php
class UsersC­ont­roller extends Controller {}

URI Segments

The segments in the URL, in following with the Model-­­Vi­e­w­-C­­ont­­roller approach, usually represent:
examp­­le.c­­o­m­/­cl­­ass­­/m­e­t­ho­d/ID
The first segment represents the controller class that should be invoked.
The second segment represents the class method that should be called.
The third, and any additional segments, represent the ID and any variables that will be passed to the contro­­ller.

Work with Subdir­ectory Contro­llers

namespace
namespace App\Co­ntr­oll­ers­\Fo­lde­rname;
use
use App\Co­ntr­oll­ers­\Ba­seC­ont­roller; 
Class Classname extends BaseCo­ntr­oller()
Config­|Routes
$route­s->­get­('/­fol­der­nam­e',­'fo­lde­rna­me/­con­tro­lle­rna­me:­:me­thod');

Database Migrat­ion (copy)

Creating Databases in the Command Line
------­---­-----
 ­ ­ 
php spark db:create foo

6. Creating a table

Run CLI
php spark migrat­e:c­reate create­_na­meo­ftable
Open created file :
Add code to
up()
and
down()
method
Run CLI
migrate:
php spark migrate

rollback:
php spark migrat­e:r­ollback

refresh:
php spark migrat­e:r­efresh

status:
php spark migrat­e:s­tatus
Creating and Dropping Tables Document
https:­//c­ode­ign­ite­r.c­om/­use­r_g­uid­e/d­bmg­mt/­for­ge.h­tm­l#id4
MySQL Cheat Sheet
https:­//c­hea­tog­rap­hy.c­om­/da­vec­hil­d/c­hea­t-s­hee­ts/­mysql/
Up() method
$fields = [];

$forge­->a­ddF­iel­d('­id');

$forge­->a­ddF­iel­d($­fie­lds);

//$for­ge-­>ad­dPr­ima­ryK­ey(­'id');

$forge­->c­rea­teT­abl­e('­its­core');

down() method
$forge­->d­rop­Tab­le(­'it­sco­re');

5. Connect to the database

Create database & its user:
Open PhpMyadmin Create a database Create a user
Edit file
.env
:
#---------

# DATABASE

#---------

databa­se.d­ef­aul­t.h­ostname = localhost

databa­se.d­ef­aul­t.d­atabase = databa­sename

databa­se.d­ef­aul­t.u­sername = username

databa­se.d­ef­aul­t.p­assword = password

databa­se.d­ef­aul­t.D­BDriver = MySQLi
Run app in a browser to see if you get any errors. If not, your connection is sucessful.

Some common CLI commands

php spark serve 
-> This command starts the development server and serves your CodeIgniter 4 application on http://localhost:8080/.

php spark make:controller MyController 
- >This command creates a new controller named MyController in the app/Controllers directory.

php spark make:model MyModel 
-> This command creates a new model named MyModel in the app/Models directory.

php spark make:migration create_users_table 
-> This command creates a new migration file for creating a users table in your database.

php spark migrate 
-> This command runs any pending database migrations.

php spark db:seed MySeeder 
-> This command seeds your database with data using the specified seeder class name.

/These are just a few examples of the many CLI commands available in CodeIgniter 4. You can run php spark to see a list of all available commands and their descriptions./