Codelgniter 4 (CI4) Complete Beginner's Guid Step-by-Step, Fully Detailed

Your First Steps with CodeIgniter 4: A Beginner's Guide π
Welcome! π If you're looking to dive into PHP web development with a framework that's modern, fast, and known for being beginner-friendly, you've come to the right place. This guide is designed for absolute beginners wanting to learn CodeIgniter 4 (CI4), breaking down the essential concepts step-by-step.
What is CodeIgniter 4? π€
CodeIgniter 4 is a powerful PHP framework built for developers who need a simple and elegant toolkit to create full-featured web applications.1 It's lightweight, boasts impressive performance, and follows the popular MVC (Model-View-Controller) architectural pattern:
- Model πΎ: Manages your application's data, typically interacting with a database.
- View π: Represents the information being presented to the user (HTML, CSS, etc.).
- Controller βοΈ: Acts as the intermediary, handling user requests, processing data (often using Models), and loading the appropriate Views.
Why Choose CodeIgniter 4? π
- Easy to Learn β : Simple structure and excellent documentation make it approachable.
- Rapid Development β‘: Comes with built-in libraries for common tasks (database, sessions, security, etc.), speeding up development.
- Great Performance π¨: Designed to be lean and fast.
- Modern PHP β¨: Built for PHP 7.4+ and incorporates modern features like namespaces and Composer integration.
Getting Started: Setting Up CodeIgniter 4 π οΈ
There are two primary ways to get CI4 onto your system:
Method 1: Using Composer (Recommended) β¨
Composer is a dependency manager for PHP. If you have it installed, this is the easiest way.
- Open your terminal or command prompt π».
- Navigate to the directory where you want to create your project.
- Run the command: Bash
composer create-project codeigniter4/appstarter your-project-name
Replaceyour-project-name
with the desired name for your application folder. Composer will download CI4 and its dependencies into that folder.
Method 2: Manual Download πΎ
- Go to the official CodeIgniter download page:
https://codeigniter.com/download - Download the latest version of CodeIgniter 4.
- Extract the downloaded ZIP file into your web server's document root (e.g.,
htdocs
for XAMPP,www
for WAMP/MAMP).
Running Your First CI4 Application βΆοΈ
CodeIgniter comes with a handy local development server.
- Open your terminal or command prompt π».
- Navigate into your project directory: Bash
cd your-project-name
- Start the server using Spark, CI4's command-line tool: Bash
php spark serve
- Open your web browser and go to
http://localhost:8080
π.
You should see the default CodeIgniter welcome page! π This confirms your installation is working.
Understanding the Project Structure π
Inside your project folder, you'll find several directories. Here are the most important ones for beginners:
app/
: This is where most of your application code will live. πControllers/
: Contains your controller classes. βοΈModels/
: Contains your model classes for database interaction. πΎViews/
: Contains your view files (HTML templates). π¨Config/
: Holds configuration files (like database settings, routing rules). π§
public/
: This is the web-accessible folder (your web server's document root should point here in production). It contains the mainindex.php
file, along with assets like CSS, JavaScript, and images. π³writable/
: Used by the framework to store cache files, logs, and session data. Ensure this directory is writable by your web server. πsystem/
: Contains the core framework files. You generally shouldn't modify anything here. ζ ΈεΏ.env
: (Pronounced "dot-env") A crucial file for environment configuration. You'll configure your database connection and other settings here. π Note: When you first install, this file might be namedenv
. You should rename it to.env
.
CodeIgniter 4 Basics: Building Blocks π§±
Let's create a simple "Hello World" example using MVC.
1. Create a Controller βοΈ
Controllers handle incoming requests.
- Go to the
app/Controllers/
directory. - Create a new file named
Greeting.php
. - Add the following code:
<?php
namespace App\Controllers;
class Greeting extends BaseController
{
public function index()
{
return "Hello, CodeIgniter 4 World!";
}
}
namespace App\Controllers;
declares the namespace, matching the folder structure.class Greeting extends BaseController
defines our controller class, inheriting helpful methods from theBaseController
.public function index()
is the default method that runs if no specific method is mentioned in the URL.
2. Routing: Mapping URLs to Controllers πΊοΈ
Routes tell CodeIgniter which controller method to execute for a given URL.
- Open the
app/Config/Routes.php
file. - Find the section with
$routes->get(...)
. - Add a new route:
// Add this line
$routes->get('/sayhello', 'Greeting::index');
This tells CI4 that when someone visits http://localhost:8080/sayhello
, it should execute the index()
method inside the Greeting
controller.
Now, navigate to http://localhost:8080/sayhello
in your browser. You should see "Hello, CodeIgniter 4 World!". π
3. Create a View π¨
Views separate presentation logic (HTML) from your controller.
- Go to the
app/Views/
directory. - Create a new file named
greeting_view.php
. - Add some simple HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My CI4 Greeting</title>
</head>
<body>
<h1>Welcome from the View!</h1>
<p>This message is rendered by a CodeIgniter 4 View file.</p>
</body>
</html>
4. Load the View from the Controller βοΈβ‘οΈπ¨
Modify your Greeting.php
controller to load the view instead of just returning text.
- Open
app/Controllers/Greeting.php
. - Update the
index()
method:
<?php
namespace App\Controllers;
class Greeting extends BaseController
{
public function index()
{
// The view() function loads a view file
// It looks for 'greeting_view.php' in app/Views/
return view('greeting_view');
}
}
Now, refresh http://localhost:8080/sayhello
in your browser. You should see the HTML content from your greeting_view.php
file. β¨
5. Connecting to a Database and Using Models πΎ
Models are used to interact with your database tables.
-
Configure Database: π§
- Rename the
env
file in your project root to.env
. - Open
.env
π and find the database section (lines starting with# database.
). - Remove the
#
at the beginning of the necessary lines and fill in your database credentials:Code snippetdatabase.default.hostname = localhost database.default.database = your_database_name database.default.username = your_db_username database.default.password = your_db_password database.default.DBDriver = MySQLi # Or PostgreSQL, SQLite3, etc. database.default.DBPrefix =
- Rename the
-
Create a Database Table: ποΈ (Example using MySQL)
SQLCREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) UNIQUE, created_at DATETIME DEFAULT CURRENT_TIMESTAMP );
-
Create a Model: π§±
- Go to
app/Models/
. - Create a file named
UserModel.php
. - Add the following code:
PHP<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model { protected $table = 'users'; // Table name protected $primaryKey = 'id'; // Primary key column protected $allowedFields = ['name', 'email']; // Fields allowed for mass assignment // (Optional) Enable timestamps protected $useTimestamps = false; // Set to true if you have created_at/updated_at fields managed by CI }
- Go to
-
Using the Model in a Controller: βοΈβ‘οΈπΎ (Example to fetch all users)
Let's modify our Greeting controller to fetch users (assuming you added some data to your users table).
PHP<?php namespace App\Controllers; // Import the UserModel use App\Models\UserModel; class Greeting extends BaseController { public function showUsers() // New method to show users { $userModel = new UserModel(); // Create an instance of the model $data['users'] = $userModel->findAll(); // Fetch all records // Pass the $data array to the view // We need a new view file: app/Views/users_list.php return view('users_list', $data); } // Keep the index method if you still want the simple greeting public function index() { return view('greeting_view'); } }
- You would also need to create the
app/Views/users_list.php
view file to display the$users
data and add a route inapp/Config/Routes.php
like$routes->get('/users', 'Greeting::showUsers');
.
- You would also need to create the
Tips for Success π‘
- Read the Docs π: The official CodeIgniter 4 documentation is excellent. Make it your best friend.
- Practice πͺ: Build small, simple projects to reinforce what you learn.
- Use Spark β¨: Explore other
php spark
commands (like creating controllers, models, migrations). - Debugging π: Ensure
CI_ENVIRONMENT
is set todevelopment
in your.env
file to see detailed error messages during development. - Learn Composer π¦: Understanding Composer helps manage PHP packages effectively.
Conclusion π
You've taken your first steps into the world of CodeIgniter 4! We've covered installation, running the development server, understanding the basic file structure, and the fundamentals of MVC: Controllers, Views, Routes, and Models for database interaction.
CodeIgniter 4 offers a fantastic balance of simplicity and power. Keep experimenting, refer to the documentation, and build something amazing. Good luck! π