CodeIgniter 3: The Home Page Part 1

So now that we have a basic understanding of what the different parts of CodeIgniter are, we can get down to writing our first controller. The Home controller. This will be where the user lands when they visit our site.

The first thing we need to do is delete the default controller called Welcome.php. This can be found in the application/controllers directory. Once that’s deleted, open up a new file, in the same directory, and call it Home.php. Next open up the routes.php file in the config folder and change to default route to home instead of welcome.
A quick aside about controllers. All controllers must define their class (as you will see below). If no function within the controller is called, it defaults to the index() function.

So first off copy the following code into the controller

<?php defined('BASEPATH') OR exit('No direct script access allowed.')
class Home extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model("home_model");
    }
    public function index() {
        $his->load->view("home");
    }
}

The first function, or the construct function, is called whenever the controller is accessed, regardless of the function. This is the construct function. Any libraries or helpers required in the module should be loaded here as well as any other code that you might need across the controller. In the above code, a model is loaded as this will be needed in almost every function within this controller. Always make sure you call the parent classes, CI_Controller’s construct function too! If you don’t do this you will get lots of errors complaining about $this.

The second function, or the index function, is called by default if no method is supplied in the URL. In this function all we are doing is loading a view for the user. All views live in the application/views folder and must be php files. Further down the line, this function will grab all the necessary data from the model and pass it to the view to be rendered.

Now that we have our controller, we need to create the model and the view otherwise when we go to our site all we will get is an error. Head over here to continue with the series.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s