This tutorial aims to guide you through the process of building a simple web application using CodeIgniter, a powerful PHP framework with a very small footprint.
By the end of this tutorial, you should be able to understand and implement the MVC (Model-View-Controller) architecture, create controllers, views, and build applications with CodeIgniter.
Before you start, you should have a basic understanding of PHP and MySQL. Familiarity with OOP (Object Oriented Programming) concepts would be beneficial but is not mandatory.
To start off, download the latest version of CodeIgniter from the official website and extract it into your localhost directory.
CodeIgniter uses the MVC (Model-View-Controller) architecture.
In CodeIgniter, the first step is to create a controller. A controller is simply a class that helps delegate work. It is the stick that stirs the drink.
//Filename: application/controllers/Hello.php
<?php
class Hello extends CI_Controller {
public function index() {
echo "Hello, World!";
}
}
The above controller (Hello.php
) has a function index()
. When this controller is called from a URL, the index()
function is executed by default.
A View is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In other words, views are the pages that the user sees and interacts with.
//Filename: application/views/hello_view.php
<html>
<head>
<title>My Simple CodeIgniter App</title>
</head>
<body>
<h2>Hello, World!</h2>
</body>
</html>
This is a simple view that will display "Hello, World!" when called.
To load a view, we use the $this->load->view()
function in our controller.
//Filename: application/controllers/Hello.php
<?php
class Hello extends CI_Controller {
public function index() {
$this->load->view('hello_view');
}
}
When the index()
function of the Hello
controller is called, it will load hello_view.php
.
We can pass data to the view by sending an array or an object to the second argument of the $this->load->view()
function.
//Filename: application/controllers/Hello.php
<?php
class Hello extends CI_Controller {
public function index() {
$data['message'] = 'Hello, World!';
$this->load->view('hello_view', $data);
}
}
In the view, we can display this data like so:
//Filename: application/views/hello_view.php
<html>
<head>
<title>My Simple CodeIgniter App</title>
</head>
<body>
<h2><?php echo $message; ?></h2>
</body>
</html>
This will display "Hello, World!".
In this tutorial, we have covered the basics of CodeIgniter including its installation, understanding MVC architecture, creating controllers, and views. The next steps would be to learn about Models and how to interact with a database using CodeIgniter's built-in classes.
Welcome
that loads a view named welcome_message
.Welcome
controller to pass a custom welcome message to the welcome_message
view. Display this message in the view.header
view and a body
view).Remember, practice is key to mastering any programming language or framework. Happy coding!