- CodeIgniter Web Application Blueprints
- Rob Foster
- 1128字
- 2021-08-06 19:34:30
Creating controllers
There are two controllers in this project. The first one create
is responsible for displaying the initial form to the user and validating the input. The second one go
will redirect the user to the original URL.
Don't forget that the controllers extend the core/MY_Controller.php
file and inherit the helpers loaded there.
Creating the controller file–controllers/create.php
The create
controller in this project is responsible for the initial contact with the user; that is to say, it loads the view file views/create.php
(that displays the form to the user) and processes the input—validation and more. We'll look at it in a second, but first let's create the controller:
Create the controller file create.php
and add the following code to it:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Create extends MY_Controller { function __construct() { parent::__construct(); $this->load->helper('string'); $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>'); } public function index() { $this->form_validation->set_rules('url_address', $this->lang->line('create_url_address'), 'required|min_length[1]|max_length[1000]|trim'); if ($this->form_validation->run() == FALSE) { // Set initial values for the view $page_data = array('success_fail' => null, 'encoded_url' => false); $this->load->view('common/header'); $this->load->view('nav/top_nav'); $this->load->view('create/create', $page_data); $this->load->view('common/footer'); } else { // Begin to build data to be passed to database $data = array( 'url_address' => $this->input->post('url_address'), ); $this->load->model('Urls_model'); if ($res = $this->Urls_model->save_url($data)) { $page_data['success_fail'] = 'success'; $page_data['encoded_url'] = $res; } else { // Some sort of error, set to display error message $page_data['success_fail'] = 'fail'; } // Build link which will be displayed to the user $page_data['encoded_url'] = base_url() . '/' . $res; $this->load->view('common/header'); $this->load->view('nav/top_nav'); $this->load->view('create/create', $page_data); $this->load->view('common/footer'); } } }
So, the create
controller does the following things for us:
Let's go through the controller by taking a look at what happens when the controller is loaded. As we're using CodeIgniter's form validation processes, you'll be aware that ($this->form_validation->run() == FALSE)
will trigger the view files to be displayed, as shown here:
if ($this->form_validation->run() == FALSE) { // Set initial values for the view $page_data = array('success_fail' => null, 'encoded_url' => false); $this->load->view('common/header'); $this->load->view('nav/top_nav'); $this->load->view('create/create', $page_data); $this->load->view('common/footer'); } else { ...
Before we display the view files, we set some variable values for the view file create/create.php
. These values govern how the success and error messages are displayed. These are stored in the $page_data
array (see the bold text in the preceding code).
Assuming there were no errors from the form validation, we grab the url_address
from the post array and package it into an array, as follows:
$data = array( 'url_address' => $this->input->post('url_address'), );
We then load the Urls_model
and send the $data
array to the save_url()
function of Urls_model
:
$this->load->model('Urls_model'); if ($res = $this->Urls_model->save_url($data)) { $page_data['success_fail'] = 'success'; $page_data['encoded_url'] = $res; } else { $page_data['success_fail'] = 'fail'; }
When successful, the model will return the url_code
that we store in $page_data['encoded_url']
.
This is then passed the create/create.php
view file, which will display a success message to the user and their now shortened URL.
Creating the controller file–controllers/go.php
The go
controller is the other end of the process. That is to say, the create.php
controller creates the shortened URL and saves it to the database, and the go.php
controller is responsible for taking a URL, finding the $url_code
in the uri
segments, looking in the database to see if it exists, and, if so, redirecting the user to the actual web address associated with it. Sounds simple, and in truth it is.
Create the go.php
controller file and add the following code to it:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Go extends MY_Controller { function __construct() { parent::__construct(); $this->load->helper('string'); } public function index() { if (!$this->uri->segment(1)) { redirect (base_url()); } else { $url_code = $this->uri->segment(1); $this->load->model('Urls_model'); $query = $this->Urls_model->fetch_url($url_code); if ($query->num_rows() == 1) { foreach ($query->result() as $row) { $url_address = $row->url_address; } redirect (prep_url($url_address)); } else { $page_data = array('success_fail' => null, 'encoded_url' => false); $this->load->view('common/header'); $this->load->view('nav/top_nav'); $this->load->view('create/create', $page_data); $this->load->view('common/footer'); } } } }
The go
controller really only gets going after the following lines:
if (!$this->uri->segment(1)) { redirect (base_url()); } else { ...
The preceding lines check to see if there is a 1st segment in the URL. Normally, the first and second segments are taken up by the controller and function name (as the order in the URL usually goes controller/function/parameter). However, as we want the URL to be short (or at least that's the idea), we're taking our unique code from the first parameter. Think of it as shifting what would normally be in the third parameter to the left. So, two levels higher up means that what was in the third segment is now at the first.
How do we do this? How do we have a parameter (our unique code) as the 1st parameter instead of the controller name? Where did the controller and function names go and why does it still work when they're removed?
We alter the routes.php
file, of course; this is explained earlier in this chapter.
Anyway, let's return to our code. If there is no item in the URL, then there isn't really anything for this controller to do. Thus, we'll redirect the user to the base_url()
function, which will load the default controller (set as autoload.php
); in this case, the default controller is the create.php
file.
Now, assuming that there was a 1st parameter, we'll move on to the next part of the controller, the bit that works out the $url_code
, as shown in the following code:
$url_code = $this->uri->segment(1); $this->load->model('Urls_model'); $query = $this->Urls_model->fetch_url($url_code); if ($query->num_rows() == 1) { foreach ($query->result() as $row) { $url_address = $row->url_address; } redirect (prep_url($url_address)); } else { ...
Take a look at the preceding code. We grab the 1st uri
segment and assign it to the $url_code
variable. We need to check if this code exists in the database, so we load the Urls_model
and call the fetch_url()
function of Urls_model
, passing to it $url_code
.
The fetch_url()
method will look in the database for a record corresponding to the value in $url_code
. If nothing is found, it'll return false,
causing the controller to load the create/create.php
view.
However, if a record is found, fetch_url()
returns the Active Record object. We now loop over the object, picking out the url_address
, and storing it as the local variable $url_address
, as shown here:
foreach ($query->result() as $row) { $url_address = $row->url_address; }
Now, we have the original URL in the $url_address
variable. We simply pass this directly to the redirect()
CodeIgniter function, which will, as the name suggests, redirect the user to the original URL.
Notice the use of the prep_url()
CodeIgniter function from within the redirect()
function. This can be done as follows:
redirect (prep_url($url_address));
The prep_url()
function will ensure that there is http://
at the beginning of the URL, if it does not already have it
- Python機器學習:數據分析與評分卡建模(微課版)
- Angular UI Development with PrimeNG
- Offer來了:Java面試核心知識點精講(原理篇)
- Python網絡爬蟲從入門到實踐(第2版)
- Oracle Database 12c Security Cookbook
- 零基礎學單片機C語言程序設計
- 深入RabbitMQ
- 編程與類型系統
- Node學習指南(第2版)
- Instant Automapper
- Practical Predictive Analytics
- Application Development with Parse using iOS SDK
- 零基礎學C++(升級版)
- Python預測之美:數據分析與算法實戰(雙色)
- INSTANT JQuery Flot Visual Data Analysis