This Simple tutorial will primarily focus on:
- Model-View-Controller basics
- Routing basics
- Form validation
- Performing basic database queries using “Query Builder”
Adding logic to the controller :
Create a file at application-package_folder/controllers/Pages.php with the following code.
<?php
class Pages extends CI_Controller {
public function view($page = 'home')
{
}
}
You have created a class named Pages, with a view method that accepts one argument named $page. The Pages class is extending the CI_Controller class. This means that the new pages class can access the methods and variables defined in the CI_Controller class (system/core/Controller.php).
The controller is what will become the center of every request to your web application. In very technical CodeIgniter discussions, it may be referred to as the super object. Like any php class, you refer to it within your controllers as $this. Referring to $this is how you will load libraries, views, and generally command the framework.
Now you’ve created your first method, it’s time to make some basic page templates. We will be creating two “views” (page templates) that act as our page footer and header.
Create the header at application/views/templates/header.php and add the following code:
<html>
<head>
<title>CodeIgniter Tutorial</title>
</head>
<body>
<h1><?php echo $title; ?></h1>
The header contains the basic HTML code that you’ll want to display before loading the main view, together with a heading. It will also output the $title variable, which we’ll define later in the controller. Now, create a footer at application/views/templates/footer.php that includes the following code:
<em>© 2015</em>
</body>
</html>
Adding logic to the view
Earlier you set up a controller with a view() method. The method accepts one parameter, which is the name of the page to be loaded. The static page templates will be located in the application-package_folder >/views/pages/ directory.
In that directory, create two files named home.php and about.php. Within those files, type some text − anything you’d like − and save them. If you like to be particularly un-original, try “Hello World!”.
In order to load those pages, you’ll have to check whether the requested page actually exists:
public function view($page = 'home')
{
if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
Now, when the page does exist, it is loaded, including the header and footer, and displayed to the user. If the page doesn’t exist, a “404 Page not found” error is shown.
The first line in this method checks whether the page actually exists. PHP’s native file_exists() function is used to check whether the file is where it’s expected to be. show_404() is a built-in CodeIgniter function that renders the default error page.
In the header template, the $title variable was used to customize the page title. The value of title is defined in this method, but instead of assigning the value to a variable, it is assigned to the title element in the $data array.
The last thing that has to be done is loading the views in the order they should be displayed. The second parameter in the view() method is used to pass values to the view. Each value in the $data array is assigned to a variable with the name of its key. So the value of $data['title'] in the controller is equivalent to $title in the view.
Routing
The controller is now functioning! Point your browser to [your-site-url]index.php/pages/view to see your page. When you visit index.php/pages/view/about you’ll see the about page, again including the header and footer.
Using custom routing rules, you have the power to map any URI to any controller and method, and break free from the normal convention:http://localhost/[controller-class]/[controller-method]/[arguments]
Let’s do that. Open the routing file located at application/config/routes.php and add the following two lines. Remove all other code that sets any element in the $route array.
$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';
CodeIgniter reads its routing rules from top to bottom and routes the request to the first matching rule. Each rule is a regular expression (left-side) mapped to a controller and method name separated by slashes (right-side). When a request comes in, CodeIgniter looks for the first match, and calls the appropriate controller and method, possibly with arguments.
Here, the second rule in the $routes array matches any request using the wildcard string (:any). and passes the parameter to the view() method of the Pages class.
Now visit index.php/about. Did it get routed correctly to the view() method in the pages controller? Awesome!
Setting up your model
Instead of writing database operations right in the controller, queries should be placed in a model, so they can easily be reused later. Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.
Open up the application-package_folder/models/ directory and create a new file called New_model.php and add the following code. Make sure you’ve configured your database properly as described here.
<?php
class New_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
}
This code looks similar to the controller code that was used earlier. It creates a new model by extending CI_Model and loads the database library. This will make the database class available through the $this->db object.
Before querying the database, Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:
$this->db->select('*');
$this->db->from('<table_name>');
/* db->where() function :
Identical to the above function except that it permits you to add a “where” clause in the second parameter, instead of using the db->where() function: only retrieve where condition records from a table
$this->db->where('<table_field_name>', $value);
*/
$data_record = $this->db->get();
return $data_record;
Add the following code to your model.
public function get_new($slug = FALSE)
{
if ($slug != FALSE)
{
$this->db->where('name', $slug);
}
$this->db->select('*');
$this->db->from('new_table');
$data_record = $this->db->get();
return $data_record;
};
Display the new API
Now that the queries are written, the model should be tied to the views that are going to display the news items to the user. This could be done in our Pages controller created earlier, but for the sake of clarity, a new New_api controller is defined. Create the new controller at application-package_folder/controllers/New_api.php.
<?php
class New_api extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('new_model');
$this->load->helper('url_helper');
}
public function index()
{
$data['new'] = $this->new_model->get_new();
}
public function view($slug = NULL)
{
$data['new_item'] = $this->new_model->get_new($slug);
}
}
Looking at the code, you may see some similarity with the files we created earlier. First, the __construct() method: it calls the constructor of its parent class (CI_Controller) and loads the model, so it can be used in all other methods in this controller. It also loads a collection of URL Helper functions, because we’ll use one of them in a view later.
Next, there are two methods to view all new items and one for a specific news item. You can see that the $slug variable is passed to the model’s method in the second method. The model is using this slug to identify the new_table item to be returned.
Now the data is retrieved by the controller through our model, but nothing is displayed yet. The next thing to do is passing this data to the views.
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('new_api', $data);
$this->load->view('templates/footer');
}
The code above gets all new_table records from the model and assigns it to a variable. The value for the title is also assigned to the $data['title'] element and all data is passed to the views. You now need to create a view to render the new_table items. Create application-package_folder/views/new_api.php and add the next piece of code.
<h2><?php echo $title; ?></h2>
<?php foreach ($news as $news_item): ?>
<h3><?php echo $news_item['title']; ?></h3>
<div class="main">
<?php echo $news_item['text']; ?>
</div>
<p><a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View article</a></p>
<?php endforeach; ?>
Instead of calling the get_new() method without a parameter, the $slug variable is passed, so it will return the specific new_table record data item. The only things left to do is create the corresponding view at application-package_folder/views/new_view.php. Put the following code in this file.
<?php
echo '<h2>'.$new_item['title'].'</h2>';
echo $new_item['text'];
Routing
Because of the wildcard routing rule created earlier, you need an extra route to view the controller that you just made. Modify your routing file (application/config/routes.php) so it looks as follows. This makes sure the requests reaches the New_api controller instead of going directly to the Pages controller. The first line routes URI’s with a slug to the view() method in the New_api controller.
$route['new/(:any)'] = '<application_type_api_package_folder>/new_api/view/$1';
$route['new'] = '<application_type_api_package_folder>/new';
$route['(:any)'] = '<application_type_api_package_folder>/pages/view/$1';
$route['default_controller'] = '<application_type_api_package_folder>/pages/view';
Point your browser to your document root, followed by index.php/news and watch your news page.
Infotrench is the best Codeigniter Development Company and provides the best services in Australia, UK, USA, Delhi, Noida, Gurugram, Ghaziabad, Faridabad. Contact us now!
ReplyDeleteCodeigniter development company