CodeIgniter – Form Validation ”; Previous Next Validation is an important process while building web application. It ensures that the data that we are getting is proper and valid to store or process. CodeIgniter has made this task very easy. Let us understand this process with a simple example. Example Create a view file myform.php and save the below code it in application/views/myform.php. This page will display form where user can submit his name and we will validate this page to ensure that it should not be empty while submitting. <html> <head> <title>My Form</title> </head> <body> <form action = “” method = “”> <?php echo validation_errors(); ?> <?php echo form_open(”form”); ?> <h5>Name</h5> <input type = “text” name = “name” value = “” size = “50” /> <div><input type = “submit” value = “Submit” /></div> </form> </body> </html> Create a view file formsuccess.php and save it in application/views/formsuccess.php. This page will be displayed if the form is validated successfully. <html> <head> <title>My Form</title> </head> <body> <h3>Your form was successfully submitted!</h3> <p><?php echo anchor(”form”, ”Try it again!”); ?></p> </body> </html> Create a controller file Form.php and save it in application/controller/Form.php. This form will either, show errors if it is not validated properly or redirected to formsuccess.php page. <?php class Form extends CI_Controller { public function index() { /* Load form helper */ $this->load->helper(array(”form”)); /* Load form validation library */ $this->load->library(”form_validation”); /* Set validation rule for name field in the form */ $this->form_validation->set_rules(”name”, ”Name”, ”required”); if ($this->form_validation->run() == FALSE) { $this->load->view(”myform”); } else { $this->load->view(”formsuccess”); } } } ?> Add the following line in application/config/routes.php. $route[”validation”] = ”Form”; Let us execute this example by visiting the following URL in the browser. This URL may be different based on your site. http://yoursite.com/index.php/validation It will produce the following screen − We have added a validation in the controller − Name is required field before submitting the form. So, if you click the submit button without entering anything in the name field, then you will be asked to enter the name before submitting as shown in the screen below. After entering the name successfully, you will be redirected to the screen as shown below. In the above example, we have used the required rule setting. There are many rules available in the CodeIgniter, which are described below. Validation Rule Reference The following is a list of all the native rules that are available to use − Given below are the most commonly used list of native rules available to use. Rule Parameter Description Example required No Returns FALSE if the form element is empty. matches Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item] regex_match Yes Returns FALSE if the form element does not match the regular expression. regex_match[/regex/] differs Yes Returns FALSE if the form element does not differ from the one in the parameter. differs[form_item] is_unique Yes Returns FALSE if the form element is not unique to the table and field name in the parameter. Note − This rule requires Query Builder to be enabled in order to work. is_unique[table.field] min_length Yes Returns FALSE if the form element is shorter than the parameter value. min_length[3] max_length Yes Returns FALSE if the form element is longer than the parameter value. max_length[12] exact_length Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8] greater_than Yes Returns FALSE if the form element is less than or equal to the parameter value or not numeric. greater_than[8] greater_than_equal_to Yes Returns FALSE if the form element is less than the parameter value, or not numeric. greater_than_equal_to[8] less_than Yes Returns FALSE if the form element is greater than or equal to the parameter value or not numeric. less_than[8] less_than_equal_to Yes Returns FALSE if the form element is greater than the parameter value, or not numeric. less_than_equal_to[8] in_list Yes Returns FALSE if the form element is not within a predetermined list. in_list[red,blue,green] alpha No Returns FALSE if the form element contains anything other than alphabetical characters. alpha_numeric No Returns FALSE if the form element contains anything other than alphanumeric characters. alpha_numeric_spaces No Returns FALSE if the form element contains anything other than alphanumeric characters or spaces. Should be used after trim to avoid spaces at the beginning or end alpha_dash No Returns FALSE if the form element contains anything other than alphanumeric characters, underscores or dashes. numeric No Returns FALSE if the form element contains anything other than numeric characters. integer No Returns FALSE if the form element contains anything other than an integer. decimal No Returns FALSE if the form element contains anything other than a decimal number. is_natural No Returns FALSE if the form element contains anything other than a natural number − 0, 1, 2, 3, etc. is_natural_no_zero No Returns FALSE if the form element contains anything other than a natural number, but not zero − 1, 2, 3, etc. valid_url No Returns FALSE if the form element does not contain a valid URL. valid_email No Returns FALSE if the form element does not contain a valid email address. valid_emails No Returns FALSE if any value provided in a comma-separated list is not a valid email. valid_ip No Returns FALSE if the supplied IP is not valid. Accepts an optional parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format. valid_base64 No Returns FALSE if the supplied string contains anything other than valid Base64 characters. Print Page Previous Next Advertisements ”;
Category: codeigniter
CodeIgniter – Internationalization ”; Previous Next The language class in CodeIgniter provides an easy way to support multiple languages for internationalization. To some extent, we can use different language files to display text in many different languages. We can put different language files in application/language directory. System language files can be found at system/language directory, but to add your own language to your application, you should create a separate folder for each language in application/language directory. Creating files Language To create a language file, you must end it with _lang.php. For example, you want to create a language file for French language, then you must save it with french_lang.php. Within this file you can store all your language texts in key, value combination in $lang array as shown below. $lang[‘key’] = ‘val’; Loading Language file To use any of the language in your application, you must first load the file of that particular language to retrieve various texts stored in that file. You can use the following code to load the language file. $this->lang->load(”filename”, ”language”); filename − It is the name of file you want to load. Don’t use extension of file here but only name of file. Language − It is the language set containing it. Fetching Language Text To fetch a line from the language file simply execute the following code. $this->lang->line(”language_key”); Where language_key is the key parameter used to fetch value of the key in the loaded language file. Autoload Languages If you need some language globally, then you can autoload it in application/config/autoload.php file as shown below. | ———————————————————————– | Auto-load Language files | ———————————————————————– | Prototype: | $autoload[”language”] = array(”lang1”, ”lang2”); | | NOTE: Do not include the “_lang” part of your file. For example | “codeigniter_lang.php” would be referenced as array(”codeigniter”); | */ $autoload[”language”] = array(); Simply, pass the different languages to be autoloaded by CodeIgniter. Example Create a controller called Lang_controller.php and save it in application/controller/Lang_controller.php <?php class Lang_controller extends CI_Controller { public function index(){ //Load form helper $this->load->helper(”form”); //Get the selected language $language = $this->input->post(”language”); //Choose language file according to selected lanaguage if($language == “french”) $this->lang->load(”french_lang”,”french”); else if($language == “german”) $this->lang->load(”german_lang”,”german”); else $this->lang->load(”english_lang”,”english”); //Fetch the message from language file. $data[”msg”] = $this->lang->line(”msg”); $data[”language”] = $language; //Load the view file $this->load->view(”lang_view”,$data); } } ?> Create a view file called lang_view.php and save it at application/views/ lang_view.php <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8″> <title>CodeIgniter Internationalization Example</title> </head> <body> <?php echo form_open(”/lang”); ?> <select name = “language” onchange = “javascript:this.form.submit();”> <?php $lang = array(”english”=>”English”,”french”=>”French”,”german”=>”German”); foreach($lang as $key=>$val) { if($key == $language) echo “<option value = ””.$key.”” selected>”.$val.”</option>”; else echo “<option value = ””.$key.””>”.$val.”</option>”; } ?> </select> <br> <?php form_close(); echo $msg; ?> </body> </html> Create three folders called English, French, and German in application/language as shown in the figure below. Copy the below given code and save it in english_lang.php file in application/language/english folder. <?php $lang[”msg”] = “CodeIgniter Internationalization example.”; ?> Copy the below given code and save it in french_lang.php file in application/language/French folder. <?php $lang[”msg”] = “Exemple CodeIgniter internationalisation.”; ?> Copy the below given code and save it in german_lang.php file in application/language/german folder. <?php $lang[”msg”] = “CodeIgniter Internationalisierung Beispiel.”; ?> Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file. $route[”lang”] = “Lang_controller”; Execute the following URL in the browser to execute the above example. http://yoursite.com/index.php/lang It will produce an output as shown in the following screenshot. If you change the language in the dropdown list, the language of the sentence written below the dropdown will also change accordingly. Print Page Previous Next Advertisements ”;
CodeIgniter – Benchmarking
CodeIgniter – Benchmarking ”; Previous Next Setting Benchmark Points If you want to measure the time taken to execute a set of lines or memory usage, you can calculate it by using Benchmarking points in CodeIgniter. There is a separate “Benchmarking” class for this purpose in CodeIgniter. This class is loaded automatically; you do not have to load it. It can be used anywhere in your controller, view, and model classes. All you have to do is to mark a start point and end point and then execute the elapsed_time() function between these two marked points and you can get the time it took to execute that code as shown below. <?php $this->benchmark->mark(”code_start”); // Some code happens here $this->benchmark->mark(”code_end”); echo $this->benchmark->elapsed_time(”code_start”, ”code_end”); ?> To display the memory usage, use the function memory_usage() as shown in the following code. <?php echo $this->benchmark->memory_usage(); ?> Example Create a controller called Profiler_controller.php and save it in application/controller/Profiler_controller.php <?php class Profiler_controller extends CI_Controller { public function index() { //enable profiler $this->output->enable_profiler(TRUE); $this->load->view(”test”); } public function disable() { //disable profiler $this->output->enable_profiler(FALSE); $this->load->view(”test”); } } ?> Create a view file called test.php and save it at application/views/test.php <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8″> <title>CodeIgniter View Example</title> </head> <body> CodeIgniter View Example </body> </html> Change the routes.php file at application/config/routes.php to add route for the above controller and add the following line at the end of the file. $route[”profiler”] = “Profiler_controller”; $route[”profiler/disable”] = “Profiler_controller/disable” After that, you can type the following URL in the address bar of your browser to execute the example. http://yoursite.com/index.php/profiler The above URL will enable the profiler and it will produce an output as shown in the following screenshot. To disable the profiling, execute the following URL. http://yoursite.com/index.php/profiler/disable Print Page Previous Next Advertisements ”;
CodeIgniter – Flashdata
CodeIgniter – Flashdata ”; Previous Next While building web application, we need to store some data for only one time and after that we want to remove that data. For example, to display some error message or information message. In PHP, we have to do it manually but CodeIgniter has made this job simple for us. In CodeIgniter, flashdata will only be available until the next request, and it will get deleted automatically. Add Flashdata We can simply store flashdata as shown below. $this->session->mark_as_flash(”item”); mark_as_flash() function is used for this purpose, which takes only one argument of the value to be stored. We can also pass an array to store multiple values. set_flashdata() function can also be used, which takes two arguments, name and value, as shown below. We can also pass an array. $this->session->set_flashdata(”item”,”value”); Retrieve Flashdata Flashdata can be retrieved using the flashdata() function which takes one argument of the item to be fetched as shown below. flashdata() function makes sure that you are getting only flash data and not any other data. $this->session->flashdata(”item”); If you do not pass any argument, then you can get an array with the same function. Example Create a class called FlashData_Controller.php and save it at application/controller/FlashData_Controller.php. <?php class FlashData_Controller extends CI_Controller { public function index() { //Load session library $this->load->library(”session”); //redirect to home page $this->load->view(”flashdata_home”); } public function add() { //Load session library $this->load->library(”session”); $this->load->helper(”url”); //add flash data $this->session->set_flashdata(”item”,”item-value”); //redirect to home page redirect(”flashdata”); } } ?> Create a view file called flashdata_home.php and save it in application/views/ flashdata_home.php <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8″> <title>CodeIgniter Flashdata Example</title> </head> <body> Flash Data Example <h2><?php echo $this->session->flashdata(”item”); ?></h2> <a href = ”flashdata/add”>Click Here</a> to add flash data. </body> </html> Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file. $route[”flashdata”] = ”FlashData_Controller”; $route[”flashdata/add”] = ”FlashData_Controller/add”; Execute the above example by visiting the following link. Replace the yoursite.com with the URL of your site. http://yoursite.com/index.php/flashdata After visiting the above URL, you will see a screen as shown below. Click on “Click Here” link and you will see a screen as shown below. Here, in this screen you will see a value of flash data variable. Refresh the page again and you will see a screen like above and flash data variable will be removed automatically. Print Page Previous Next Advertisements ”;
CodeIgniter – Discussion
Discuss CodeIgniter ”; Previous Next CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter was created by EllisLab, and is now a project of the British Columbia Institute of Technology. Print Page Previous Next Advertisements ”;
CodeIgniter – Session Management ”; Previous Next When building websites, we often need to track user’s activity and state and for this purpose, we have to use session. CodeIgniter has session class for this purpose. Initializing a Session Sessions data are available globally through the site but to use those data we first need to initialize the session. We can do that by executing the following line in constructor. $this->load->library(”session”); After loading the session library, you can simply use the session object as shown below. $this->session Add Session Data In PHP, we simply use $_SESSION array to set any data in session as shown below. $_SESSION[‘key’] = value; Where ‘key’ is the key of array and value is assigned on right side of equal to sign. The same thing can be done in CodeIgniter as shown below. $this->session->set_userdata(”some_name”, ”some_value”); set_userdata() function takes two arguments. The first argument, some_name, is the name of the session variable, under which, some_value will be stored. set_userdata() function also supports another syntax in which you can pass array to store values as shown below. $newdata = array( ”username” => ”johndoe”, ”email” => ”[email protected]”, ”logged_in” => TRUE ); $this->session->set_userdata($newdata); Remove Session Data In PHP, we can remove data stored in session using the unset() function as shown below. unset($_SESSION[‘some_name’]); Removing session data in CodeIgniter is very simple as shown below. The below version of unset_userdata() function will remove only one variable from session. $this->session->unset_userdata(”some_name”); If you want to remove more values from session or to remove an entire array you can use the below version of unset_userdata() function. $this->session->unset_userdata($array_items); Fetch Session Data After setting data in session, we can also retrieve that data as shown below. Userdata() function will be used for this purpose. This function will return NULL if the data you are trying to access is not available. $name = $this->session->userdata(”name”); Example Create a controller class called Session_controller.php and save it in application/controller/Session_controller.php. <?php class Session_controller extends CI_Controller { public function index() { //loading session library $this->load->library(”session”); //adding data to session $this->session->set_userdata(”name”,”virat”); $this->load->view(”session_view”); } public function unset_session_data() { //loading session library $this->load->library(”session”); //removing session data $this->session->unset_userdata(”name”); $this->load->view(”session_view”); } } ?> Create a view file called session_view.php and save it in application/views/session_view.php <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8″> <title>CodeIgniter Session Example</title> </head> <body> Welcome <?php echo $this->session->userdata(”name”); ?> <br> <a href = ”http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/sessionex/unset”> Click Here</a> to unset session data. </body> </html> Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file. $route[”sessionex”] = ”Session_Controller”; Execute the above example by using the following address. Replace yoursite.com with the URL of your site. http://yoursite.com/index.php/sessionex Print Page Previous Next Advertisements ”;
CodeIgniter – Quick Guide
CodeIgniter – Quick Guide ”; Previous Next CodeIgniter – Overview CodeIgniter is an application development framework, which can be used to develop websites, using PHP. It is an Open Source framework. It has a very rich set of functionality, which will increase the speed of website development work. If you know PHP well, then CodeIgniter will make your task easier. It has a very rich set of libraries and helpers. By using CodeIgniter, you will save a lot of time, if you are developing a website from scratch. Not only that, a website built in CodeIgniter is secure too, as it has the ability to prevent various attacks that take place through websites. CodeIgniter Features Some of the important features of CodeIgniter are listed below − Model-View-Controller Based System Extremely Light Weight Full Featured database classes with support for several platforms. Query Builder Database Support Form and Data Validation Security and XSS Filtering Session Management Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more. Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM File Uploading Class FTP Class Localization Pagination Data Encryption Benchmarking Full Page Caching Error Logging Application Profiling Calendaring Class User Agent Class Zip Encoding Class Template Engine Class Trackback Class XML-RPC Library Unit Testing Class Search-engine Friendly URLs Flexible URI Routing Support for Hooks and Class Extensions Large library of “helper” functions CodeIgniter – Installing It is very easy to install CodeIgniter. Just follow the steps given below − Step-1 − Download the CodeIgniter from the link CodeIgniter Step-2 − Unzip the folder. Step-3 − Upload all files and folders to your server. Step-4 − After uploading all the files to your server, visit the URL of your server, e.g., www.domain-name.com. On visiting the URL, you will see the following screen − CodeIgniter – Application Architecture The architecture of CodeIgniter application is shown below. As shown in the figure, whenever a request comes to CodeIgniter, it will first go to index.php page. In the second step, Routing will decide whether to pass this request to step-3 for caching or to pass this request to step-4 for security check. If the requested page is already in Caching, then Routing will pass the request to step-3 and the response will go back to the user. If the requested page does not exist in Caching, then Routing will pass the requested page to step-4 for Security checks. Before passing the request to Application Controller, the Security of the submitted data is checked. After the Security check, the Application Controller loads necessary Models, Libraries, Helpers, Plugins and Scripts and pass it on to View. The View will render the page with available data and pass it on for Caching. As the requested page was not cached before so this time it will be cached in Caching, to process this page quickly for future requests. Directory Structure The image given below shows the directory structure of the CodeIgniter. CodeIgniter directory structure is divided into 3 folders − Application System User_guide Application As the name indicates the Application folder contains all the code of your application that you are building. This is the folder where you will develop your project. The Application folder contains several other folders, which are explained below − Cache − This folder contains all the cached pages of your application. These cached pages will increase the overall speed of accessing the pages. Config − This folder contains various files to configure the application. With the help of config.php file, user can configure the application. Using database.php file, user can configure the database of the application. Controllers − This folder holds the controllers of your application. It is the basic part of your application. Core − This folder will contain base class of your application. Helpers − In this folder, you can put helper class of your application. Hooks − The files in this folder provide a means to tap into and modify the inner workings of the framework without hacking the core files. Language − This folder contains language related files. Libraries − This folder contains files of the libraries developed for your application. Logs − This folder contains files related to the log of the system. Models − The database login will be placed in this folder. Third_party − In this folder, you can place any plugins, which will be used for your application. Views − Application’s HTML files will be placed in this folder. System This folder contains CodeIgniter core codes, libraries, helpers and other files, which help make the coding easy. These libraries and helpers are loaded and used in web app development. This folder contains all the CodeIgniter code of consequence, organized into various folders − Core − This folder contains CodeIgniter’s core class. Do not modify anything here. All of your work will take place in the application folder. Even if your intent is to extend the CodeIgniter core, you have to do it with hooks, and hooks live in the application folder. Database − The database folder contains core database drivers and other database utilities. Fonts − The fonts folder contains font related information and utilities. Helpers − The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers). Language − The language folder contains language files. You can ignore it for now. Libraries − The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder. User_guide This is your user guide to CodeIgniter. It is basically, the offline version of user guide on CodeIgniter website. Using this, one can learn the functions of various libraries, helpers and classes. It is recommended to go through this user guide before building your first web app in
CodeIgniter – Application Profiling ”; Previous Next When building a web application, we are very much concerned about the performance of the website in terms of how much time the controller took to execute and how much memory is used. Not only the performance, but we also need to see the insights of data like POST data, data of database queries, session data etc. for debugging purpose while developing some application. CodeIgniter has made this job easier for us by profiling an application. Enable Profiling To enable profiling of your application, simply execute the command given below in any of the method of your controller. $this->output->enable_profiler(TRUE); The report of the profiling can be seen at the bottom of the page after enabling it. Disable Profiling To disable profiling of your application, simply execute the command given below in any of the method of your controller. $this->output->enable_profiler(FALSE); Enable / Disable Profiler Section Profiling can be done on section basis. You can enable or disable profiling of a section by setting a Boolean value TRUE or FALSE. If you want to set profiling on the application then you can do in a file located in application/config/profiler.php For example, the following command will enable profiling queries for the whole application. $config[”queries”] = TRUE; In the following table, the key is the parameter, which can be set in the config array to enable or disable a particular profile. Key Description Default benchmarks Elapsed time of Benchmark points and total execution time TRUE config CodeIgniterConfig variables TRUE controller_info The Controller class and method requested TRUE get Any GET data passed in the request TRUE http_headers The HTTP headers for the current request TRUE memory_usage Amount of memory consumed by the current request, in bytes TRUE post Any POST data passed in the request TRUE queries Listing of all database queries executed, including execution time TRUE uri_string The URI of the current request TRUE session_data Data stored in the current session TRUE query_toggle_count The number of queries after which the query block will default to hidden. 25 The profiler set in the file in application/config/profiler.php can be overridden by using the set_profiler_sections() function in controllers as shown below. $sections = array( ”config” => TRUE, ”queries” => TRUE ); $this->output->set_profiler_sections($sections); Print Page Previous Next Advertisements ”;
CodeIgniter – Basic Concepts
CodeIgniter – Basic Concepts ”; Previous Next Controllers A controller is a simple class file. As the name suggests, it controls the whole application by URI. Creating a Controller First, go to application/controllers folder. You will find two files there, index.html and Welcome.php. These files come with the CodeIgniter. Keep these files as they are. Create a new file under the same path named “Test.php”. Write the following code in that file − <?php class Test extends CI_Controller { public function index() { echo “Hello World!”; } } ?> The Test class extends an in-built class called CI_Controller. This class must be extended whenever you want to make your own Controller class. Calling a Controller The above controller can be called by URI as follows − http://www.your-domain.com/index.php/test Notice the word “test” in the above URI after index.php. This indicates the class name of controller. As we have given the name of the controller “Test”, we are writing “test” after the index.php. The class name must start with uppercase letter but we need to write lowercase letter when we call that controller by URI. The general syntax for calling the controller is as follows − http://www.your-domain.com/index.php/controller/method-name Creating & Calling Constructor Method Let us modify the above class and create another method named “hello”. <?php class Test extends CI_Controller { public function index() { echo “This is default function.”; } public function hello() { echo “This is hello function.”; } } ?> We can execute the above controller in the following three ways − http://www.your-domain.com/index.php/test http://www.your-domain.com/index.php/test/index http://www.your-domain.com/index.php/test/hello After visiting the first URI in the browser, we get the output as shown in the picture given below. As you can see, we got the output of the method “index”, even though we did not pass the name of the method the URI. We have used only controller name in the URI. In such situations, the CodeIgniter calls the default method “index”. Visiting the second URI in the browser, we get the same output as shown in the above picture. Here, we have passed method’s name after controller’s name in the URI. As the name of the method is “index”, we are getting the same output. Visiting the third URI in the browser, we get the output as shown in picture given below. As you can see, we are getting the output of the method “hello” because we have passed “hello” as the method name, after the name of the controller “test” in the URI. Points to Remember The name of the controller class must start with an uppercase letter. The controller must be called with lowercase letter. Do not use the same name of the method as your parent class, as it will override parent class’s functionality. Views This can be a simple or complex webpage, which can be called by the controller. The webpage may contain header, footer, sidebar etc. View cannot be called directly. Let us create a simple view. Create a new file under application/views with name “test.php” and copy the below given code in that file. <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8″> <title>CodeIgniter View Example</title> </head> <body> CodeIgniter View Example </body> </html> Change the code of application/controllers/test.php file as shown in the below. Loading the View The view can be loaded by the following syntax − $this->load->view(”name”); Where name is the view file, which is being rendered. If you have planned to store the view file in some directory then you can use the following syntax − $this->load->view(”directory-name/name”); It is not necessary to specify the extension as php, unless something other than .php is used. The index() method is calling the view method and passing the “test” as argument to view() method because we have stored the html coding in “test.php” file under application/views/test.php. <?php class Test extends CI_Controller { public function index() { $this->load->view(”test”); } } ?> Here is the output of the above code − The following flowchart illustrates of how everything works − Models Models classes are designed to work with information in the database. As an example, if you are using CodeIgniter to manage users in your application then you must have model class, which contains functions to insert, delete, update and retrieve your users’ data. Creating Model Class Model classes are stored in application/models directory. Following code shows how to create model class in CodeIgniter. <?php Class Model_name extends CI_Model { Public function __construct() { parent::__construct(); } } ?> Where Model_name is the name of the model class that you want to give. Each model class must inherit the CodeIgniter’s CI_Model class. The first letter of the model class must be in capital letter. Following is the code for users’ model class. <?php Class User_model extends CI_Model { Public function __construct() { parent::__construct(); } } ?> The above model class must be saved as User_model.php. The class name and file name must be same. Loading Model Model can be called in controller. Following code can be used to load any model. $this->load->model(”model_name”); Where model_name is the name of the model to be loaded. After loading the model you can simply call its method as shown below. $this->model_name->method(); Auto-loading Models There may be situations where you want some model class throughout your application. In such situations, it is better if we autoload it. /* | ————————————————————— | Auto-Load Models | ————————————————————— | Prototype: | | $autoload[”model”] = array(”first_model”, ”second_model”); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload[”model”] = array(”first_model” => ”first”); */ $autoload[”model”] = array(); As shown in the above figure, pass the name of the model in the array that you want to autoload and it will be autoloaded, while system is in initialization state and is accessible throughout the application. Helpers As the name suggests, it will help you build your system. It is divided into small functions to serve different functionality. A number of helpers are available in CodeIgniter, which are
CodeIgniter – Application Architecture ”; Previous Next The architecture of CodeIgniter application is shown below. As shown in the figure, whenever a request comes to CodeIgniter, it will first go to index.php page. In the second step, Routing will decide whether to pass this request to step-3 for caching or to pass this request to step-4 for security check. If the requested page is already in Caching, then Routing will pass the request to step-3 and the response will go back to the user. If the requested page does not exist in Caching, then Routing will pass the requested page to step-4 for Security checks. Before passing the request to Application Controller, the Security of the submitted data is checked. After the Security check, the Application Controller loads necessary Models, Libraries, Helpers, Plugins and Scripts and pass it on to View. The View will render the page with available data and pass it on for Caching. As the requested page was not cached before so this time it will be cached in Caching, to process this page quickly for future requests. Directory Structure The image given below shows the directory structure of the CodeIgniter. CodeIgniter directory structure is divided into 3 folders − Application System User_guide Application As the name indicates the Application folder contains all the code of your application that you are building. This is the folder where you will develop your project. The Application folder contains several other folders, which are explained below − Cache − This folder contains all the cached pages of your application. These cached pages will increase the overall speed of accessing the pages. Config − This folder contains various files to configure the application. With the help of config.php file, user can configure the application. Using database.php file, user can configure the database of the application. Controllers − This folder holds the controllers of your application. It is the basic part of your application. Core − This folder will contain base class of your application. Helpers − In this folder, you can put helper class of your application. Hooks − The files in this folder provide a means to tap into and modify the inner workings of the framework without hacking the core files. Language − This folder contains language related files. Libraries − This folder contains files of the libraries developed for your application. Logs − This folder contains files related to the log of the system. Models − The database login will be placed in this folder. Third_party − In this folder, you can place any plugins, which will be used for your application. Views − Application’s HTML files will be placed in this folder. System This folder contains CodeIgniter core codes, libraries, helpers and other files, which help make the coding easy. These libraries and helpers are loaded and used in web app development. This folder contains all the CodeIgniter code of consequence, organized into various folders − Core − This folder contains CodeIgniter’s core class. Do not modify anything here. All of your work will take place in the application folder. Even if your intent is to extend the CodeIgniter core, you have to do it with hooks, and hooks live in the application folder. Database − The database folder contains core database drivers and other database utilities. Fonts − The fonts folder contains font related information and utilities. Helpers − The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers). Language − The language folder contains language files. You can ignore it for now. Libraries − The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder. User_guide This is your user guide to CodeIgniter. It is basically, the offline version of user guide on CodeIgniter website. Using this, one can learn the functions of various libraries, helpers and classes. It is recommended to go through this user guide before building your first web app in CodeIgniter. Beside these three folders, there is one more important file named “index.php”. In this file, we can set the application environment and error level and we can define system and application folder name. It is recommended, not to edit these settings if you do not have enough knowledge about what you are going to do. Print Page Previous Next Advertisements ”;