Tutorial 2- Controller

What is Controller

“Controllers are the ones that receive the HTTP requests, communicate with models to get the data, send it to views to generate the HTML code and return the results to the web browser.”

We have to Know something before creating a Controller

  • A Controller is a php File which is located inside your application/controllers folder.
  • That File contains a Class same named as the file excluding file extension(.php).
  • The name of the controller class and file must start with an uppercase letter. see more here
  • The class should extend core controller name CI_Controller
  • The controller can be called (browser url)  with lowercase letter.

Creating a Controller

  • Lets Create a file named Hello.php inside application/controllers
  • Now Include Following code inside that file
    <?php defined('BASEPATH') OR exit('No direct script access allowed');
    class Hello extends CI_Controller
    {
      public function index()
      {
        echo 'Hello world';
      }
    }

Calling a Controller

Codeigniter Url Should be like this

project_base_url/index.php/controler/method-name

Our project_base_url is http://localhost/ci/  or you can use your domain name if you working at your live site.

The above controller can be called by URI as follows 

http://localhost/ci/index.php/hello/index

If you hit that link you will see your browser will output

Hello world

We can remove index.php from our url. We can learn it from any of the following links

Codeigniter Default class method is index.
If we do not call method-name in the url it will call index method.
Lets create another method.
class Hello extends CI_Controller
{
    public function index()
    {
        echo 'This is default method';
    }
    public function welcome()
    {
        echo 'Welcome to CI tutorial';
    }
}

Now we Can call those function follwoing way

URL: http://localhost/ci/hello
Method: index
Output: This is default method

URL: http://localhost/ci/hello/index
Method: index
Output: This is default method

URL: http://localhost/ci/hello/welcome
Method: welcome
Output:Welcome to CI tutorial

We will learn more about controller latter at controller-advance learning.

Bookmark the permalink.

Leave a Reply

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