How to Build Controllers and Views with CodeIgniter

Now that we have the CodeIgniter configuration out of the way, let’s get started with our first controller. We’ll also create a view for it, and then we’ll pass data from the controller to the view.

Getting Started with CodeIgniterCreating a controller is fairly easy once you’ve done it a couple of times, but at first it can be a bit confusing to someone with little experience in PHP.  There are three major rules for controllers:

  • They must have names that are legal PHP class names. That means no hyphens, which doesn’t work well for creating SEO-friendly URLs.  You can work around that with routes, which we’ll get to later.
  • Their names must start with a capital letter, like a class (since controllers are classes, with methods in them).
  • Controllers must have the same name as their file name. So if your controller is named My_first_controller, your file name must be my_first_controller.php.

Controllers, logically enough, are stored in the “controllers” folder. You can have sub-folders to organize your controllers, but natively CI only supports one level. If you want more than that, you’ll have to find a router to support them. There are some available. Search for “MY_Router.php” in the CI forums or Google to find some examples.

Here’s an example of a controllers folder on a real-world project to show you how I organize things.

 CodeIgniter Controller

A few things things: In this example, the names are all lowercase. That’s a personal preference, but not a requirement. You can use camel or Pascal casing if you prefer. I use underscores to separate some of the words. Again, that’s a preference. The name of the controller doesn’t have to show up in your URL unless you want it to.

For instance, take the “about.php” controller. The route to this could be:

http://example.com/home/about

This is the same as:

http://example.com/home/about/index

The index is implied. If you had a method in the “about” controller called “foo”, the route would be:

http://example.com/home/about/foo

The “index” method is the base route of any controller, but you don’t have to have one if you don’t need it.

When you create a controller, the format is fairly simple. To start with, it’s a CI best practice to include the following line at the top of your controller for security reasons:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

The skeleton of a class looks like this:

class MyController extends CI_Controller {
public function index()
{


}
}

You place your controller code inside the “index” function. You could also have other methods below the “index” method, as I said. Those might be private functions that relate to your method.

One important note with this particular controller name: Generally, you’re not going to call your controller “MyController”. But you can. However, don’t call it “MY_Controller” with the uppercase “MY”. That’s a reserved name. You can extend some or all of your controllers from “MY_Controller.”  If you extend “MY_Controller”, then all of the controllers that extend it will have all of its functionality.  “MY_Controller” is a file that goes in your “core” folder.

Now that we know the rules, let’s create our first controller. Call it “About” and save it in the “home” sub-folder of your “controllers” folder. Using your PHP environment, the route to it will be as I described it earlier, but with your domain. Inside the “index” method, type:

echo "Hello, World!"

Display the route in your browser (assuming you’ve used a .htaccess to remove index.php) and you’ll see the message.

But that’s not very useful. You’re going to want to load data into your views. So the first thing you need to do is create a view. Let’s use some bare-boned HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $headline; ?></h1>
<p><?php echo $text; ?></p>
</body>
</html>

Take a look at what’s in the <title>, <h1> and <p> tags. There’s a PHP variable being echoed in each. And so on for the other tags. That data will be passed to the view from the controller. In the real world, it might be pulled from a database. Or it might just be static text in the controller.

To pass this data, your controller will now look like this:

CodeIgniter about.php

Note that the last line of code actually loads the view. The path to the file,”home/about”, matches the path in the “Views” folder. There’s an “about.php” file in that folder’s “home” sub-folder.  You can see the views folder structure at the bottom of the above image.

If you load this in your browser, you’ll see this:

CodeIgniter About Page

I’m keeping it simple, but you can imagine all of the bits of data you could pass to a complex page. The sky’s the limit there. I’ve seen controllers get very lengthy because they were passing so many different pieces of information to the view.

Next time, we’ll look at views in more depth and get started on models and databases.  Once we get those basics down, we can start getting more advanced. I wanted everyone to have a good grasp on the fundamentals before we started to accelerate things.

If you have any questions or comments, please post them in the comments below.

Related Links

Comments

  1. BY RobS says:

    (subscription comment)

    • BY bobby says:

      For some reason, the data from the controller is not being passed to the view. I literally see ?php echo headline; ?> etc.. when i load it. If you could offer some possible reasons that would help very much. Thanks!

  2. BY bobby says:

    please ignore the last question, i figured it out.. I missed a <… dumb move. :) thanks

Post a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>