The CI naming conventions are essential to understand and use, in order to properly develop with CI. They enable you to write minimal code using a strict and concise set of rules.
The full CI naming conventions and style guide can be found at http://codeigniter.com/user_guide/general/styleguide.html.
The naming conventions refer to the naming of parameters, functions/methods, class-related PHP file name storing code, project resource paths, and so on. Here are the specific issues we will review:
CI_controller
or CI_model
; see the examples discussed in the Controller definition naming rules section)CI defines "one class one file standard" so that every class of a CI controller extension and CI model extension of a library class resides in one file. This also applies to helpers that are a set of functions. Each resource category (controller, library, model, and view) will be located in a specific directory or its subdirectory. The most commonly used resource categories are as follows:
Let's define the initial project controller to handle some basic services. Note that the controller class name is My_handler
, and must reside in a file named my_handler.php
(all lower case) at /application/controllers
in our CI project directory. Here's the code sample with which to review the naming conventions:
class My_handler extends CI_Controller { function __construct(){ // Must Call Patent to get all its services inherited parent::__construct(); } function index () { // executed when referring to My_handlercontroller via URLecho "Hello World"; } function calc ($a = 2, $b=2) {// executed when referring to My_handler/calc via URL echo " $a * $b = ".$a*$b; } functionAJAX_calc () { // If the request is not an AJAX we shall abort! //This is done by the if (!$this->input->is_AJAX_request()) exit ('none AJAX calls rejected!'), // see http://codeigniter.com/user_guide/libraries/input.html $a = $this->input->post('a'),// get the posted a parameter$b = $this->input->post('b'),// get the posted b parameter $result = (int) $a * (int) $b; $data = array('result'=> $result);// to add more array parameters: ,'p2' => $p2, 'p3'=>$p3,.. echojson_encode($data);// return the JSON encoded array return; } } // closing the class definition
We call this controller via an HTTP request URL, as an HTTP or HTTPS request. For example: http://mydomain.com/index.php/my_handler
.
Let us review several usage scenarios with this controller class definition. Note that you can enable CodeIgniter to operate without the index.php
file in the path; for more information, refer to the index.php
file issue discussed later in this chapter. In this section we will review different use cases for the CI controller as well as the naming rules associated with the controller. The following are the cases that are mainly used for calling a controller:
The controller has its own naming rules and usage guidelines that we will review now. The controller is most commonly called from the view using an anchor tag. However, it may also be called using AJAX or even a crontab PHP script using a PHP function file or cURL-based request.
Controllers are mostly called via a user interaction session on a rendered view processed by a client browser. The controller method is called to issue another process, such as and AJAX request or processing the request and rendering it back to the client browser additional view or web page. To define the controller call within a view definition (application/views), we define an anchor to be executed by the browser per user request. Note that in these examples we use another URL helper named anchor()
.
anchor( $uri, $text, $html_attributes);
Note that in order to use the CI anchor helper function, we will initially load the helper URL via config/autoload.php
.
$autoload['helper'] = array('url'),
Another way to do this is to load the anchor helper in the controller rendering the view, where we want to use an anchor:
$this->load->helper('url'),
$URI
: The URI path to call a controller or any URI we want to execute$text
: The anchor label shown to the user to click on$html_attributes
: Any HTML attributes that can be defined for an HTML anchor elementAn example of the resulting HTML that will be executed by the client-side browser is as follows:
<a href="myapps.com/myciapp/showme" class='mybutton'> Press Me </a> <!-- where $uri = 'myapps.com/myciapp/showme'; $text = 'Press Me'; $html_attributes = "class='mybutton'";-->
Back to our example—the view code part that enables the user to call the defined controller will look like the following (the PHP portions are with other HTML tags in a view file):
<?PHP echo anchor(ase_url().' index.php/my_handler ','Press Me A'), ?>
Since we only referred to the class name, its constructor and index method, if defined, will be executed. In case we did not define an index method for this my_handler
controller, the preceding calls will only instantiate the class using its constructor definition, and if the index method was defined it will be called as well. In our case, the index method was defined so it will be called as well.
In this example, we enable the end user to call a specific class method but without parameters, so that the default method parameters must be used via the browser.
Note that in order to use any CI helper function we need to make sure that it is either autoloaded or specifically loaded in the controller (for the controller method's usage or rendered views), library, or model.
<?PHP echo anchor(base_url().' index.php/my_handler/calc ' ,'Press Me B'), ?>
Note that in order to refer to a specific My_handler
class method named calc
, we concatenated /calc
after the class name. Issuing this view from a browser we will get a result as follows: 2 * 2 = 4. Why?.
This is simply because we define default values in the receiving controller method. So that if no parameters are sent as in this example the default ones will be used, which are both set to 2
and hence the class calc
method will output 4
.
In this example we enable the end user to call a specific class method with its parameters via the browser.
<?PHP echo anchor(base_url().' index.php/my_handler/calc/5/7', 'Press Me C',); ?>
Issuing this from a browser, we will get: 5 * 7 = 35. Why?.
Since we provided 5
as the first parameter and 7
as the second, using the CI URI naming convention of spectated /
to pass parameter values to a called controller class method. Since we use the parameters as integers for multiplication, PHP casts them as integers, so we have 5 * 7 which is 35.
Note that in order to call a specific controller method with parameters, we add the /
separator after the method name followed by the parameters, and each parameter is also separated by /
.
To understand this better see the following use cases and their meanings, CI uses the URI as follows:
When issuing the URI:
<?PHP base_url() ?>/controller_name/method_name/param1/param2/../paramN
The controller named controller_name
will be instanced by CI with the controller constructor, and then the method method_name
will be called with the first parameter param1
, second parameter param2
, and so on.
On the PHP controller side, the controller_name
method prototype will look like the following example:
Publicfunction method_name($user, $name, $email, $phone) {
So that $user
= param1
, $name
= param2
, and so on.
This is one possible way to get the parameters through a URL or get an array. In CodeIgniter we don't have to get an array, so we can use the URI class to get the parameters. For reference, see http://ellislab.com/codeigniter/user-guide/libraries/uri.html.
If we provide:
<?PHP base_url() ?>/controller_name
The CI will execute only the controller constructor and the index()
method, if the controller has such a method.
If we provide:
<?PHP base_url() ?>/controller_name/method_name
The preceding code will be executed without calling the index()
method, following the call of the specific method, method_name
. Remember that we shall not use /
in our parameters for such a call and may wish to provide them using URL encode or other reversible encoding methods. We can also call our controller method using POST/GET so that we can retrieve the parameter value posted in the class method in the following way:
$param1_val = $this->input->post('param1'),
For example, within the class code we issue an AJAX call to a function as shown in the next example.
In this example we enable the end user to issue an AJAX call to a specific class method with its parameters enabled via HTTP POST
.
<script src="https://AJAX.googleapis.com/AJAX/libs/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript"> function AJAX_call () { a_val = $('[name="a"]').val(); b_val = $('[name="b"]').val(); AJAX_url = '<?PHP echo base_url()."index.php/my_handler/AJAX_calc";?>'; $.AJAX({ type: "POST",url : AJAX_url,data: {a : a_val, b : b_val },dataType: "json",success: function(data) {$('#result').html (data.result); } }); // AJAX Call end }</script> <form onsubmit="AJAX_call();"><label>Enter A</label><input type="text" name="a" /><label>Enter B</label><input type="text" name="b" />Result:<div id='result'>The Result Will Be Shown Here</div><input type="submit" value="Calculate" /></form>
Enter two numeric values for A
and B
and click on the Calculate button. We will get the integer casted as A
and multiply it by the integer casted as B
in the div
section with id='result'
.
To reuse other libraries, models, and helper capabilities in our controller, we may also want to load libraries and helpers to our controller or model class to reuse them for our needs. In case we decide that certain helpers, libraries, or models are useful, we will have them loaded automatically. We can do so in the autoload configuration file named autoload.php
located at application/config/autoload.php
in our project.
The following is an autoload configuration example:
$autoload['libraries'] = array('template','database','session'), $autoload['helper'] = array('url', 'utilities'), // Note: url helper provide base_url() service
Remember that if we want to load our helpers or libraries within a certain controller or model, we can enable it as per the following example:
classMy_handler extends CI_Controller { function __construct(){ // see previous explanation on this parent call parent::__construct(); // Loadingspecific helperto enable calling // its functions in all this // controller class methods as well as in all // rendered views. // Note how the full name and path is abbreviated: $this->load->helper('ssl_helper'), //Loading and instantiatinga library s // application/librarues/smart_handler.php to // enable calling all its class methods as from // this controller as well from all the rendered // by this controller. $this->load->library('smart_handler' ); } function enforce_ssl () { force_ssl(); // A function in the ssl_helper for more see // helpers chapter } function smarty () { //call a method smart_service in the loaded //smart_handler library //for more see Libraries chapter $this->smart_handler->smart_service($param1, $param2); } }//End Controller My_handler
We shall call the method that uses the helper as follows:
<?php echo base_url(); ?>index.php/my_handler/enforce_ssl
For smarty method calls in the loaded library, we use the following code:
<?php echo base_url(); ?>index.php/my_handler/smarty
Passing parameters within a controller into a view, application/controllers/my_controller.php
as follows:
$array = array ('a' =>100,'b' =>200); $view_params = array ('param1' => 'hello world', 'param2' =>$array ); $this->load_view('my_view', $view_params);
In the view file at application/views
: my_view.php
, the view can use the provided parameters in the following method:
<?PHP echo $param1;// will echo hello world
Note that within the controller it is defined as the param1
key array element, where the array is sent to the view.
// To get the param2 values we shall perform : foreach ( $params2 as param ){ echo param; // will echo 100 and 200 as $params2['a'] and // $params2['b'] values } ?>
18.118.31.67