Let's say that we want to have an alternative greeting that is accessible through a different URL. We might create a new function or even a new controller for that, but a best practice is to optimize what we already have, to make it work at it's best!
To do this, we'll keep the same view as in the previous examples, but we'll introduce a parameter to our function, in order for it to be able to choose between two different greetings:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Hello_world extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function greetings($my_greetings){
switch($my_greetings)
{
case 'goodbye':
$say = 'Good Bye World';
break;
case 'morning':
$say = 'Good Morning World';
break;
default:
$say = 'Hello World';
}
$data = array('greetings'=>$say);
$this->load->view('hello_world',$data);
}
}
Now we have multiple greetings options! In order for them to be visualized, we are going to add the parameter at the URL, as follows:
http://[your_domain_name]/hello_world/greetings/goodbye
This will show us the message: "Good Bye World".
The structure of the URL is as follows:
http://[your_domain_name]/[controller_name]/[function_name]/[parameter_1]
In this case, in order to get back to our good old "Hello World", it's enough to call the former url, without parameters:
http://localhost/hello_world/greetings
You can add multiple parameters to your function (for instance, if you need 3 of them):
public function greetings($param1,$param2,$param3)
and they can be filled up using the url as follows:
http://[your_domain_name]/[controller_name]/[function_name]/[param1]/[param2]/[param3]
e.g. http://localhost/hello_world/greetings/goodbye/italian/red
This way you can have parameters passed to you directly from the URL that will affect the content of what will be shown.
To know more about how to pass parameters through the URL, you might want look into the topic of routing!