Monday, March 28, 2016

Lesson 1 : Creating a Controller and View

Lets create a controller and a view.

In the Application/controllers folder, create a file named quotes.php and type the following code the file:


<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Quotes extends CI_Controller {

public function index(){
echo "When you are courting a nice girl an hour seems like a second. When you sit on a red-hot cinder a second seems like an hour. That's relativity.  <h3>Albert Einstein</h3>";
}
}

Point your browser to: http://localhost/codi/index.php/quotes. You should a see a quote you just typed.

But, we didn't make use of a view file. Let's create one: quotesview.php with following code:


<?php echo $quotes ?>



Edit the controller file like so:

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

class Quotes extends CI_Controller {
public function index(){
$quotes = "When you are courting a nice girl an hour seems like a second. When you sit on a red-hot cinder a second seems like an hour. That's relativity.  <h3>Albert Einstein</h3>";
$data['quotes']=$quotes;
$this->load->view('quotesview',$data);
}
}

Point your browser to: http://localhost/codi/index.php/quotes. You should the same quote.

This time we called the view file quotesview and passed the parameter named $data, and used printed the same with echo: <?php echo $quotes ?>

<?php echo $quotes ?>  equals to <?= $quotes ?>.

You could also use <?= $quotes ?>

You must have observed that everytime we point to a URL, we have to include index.php. In the next post we shall do something so that we don't have to type index.php every time.

No comments:

Post a Comment