Home  >  Article  >  Backend Development  >  Summary of some excellent features of Codeigniter, codeigniter summary_PHP tutorial

Summary of some excellent features of Codeigniter, codeigniter summary_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:09:31868browse

Summary of some excellent features of Codeigniter, summary of codeigniter

Recently I am planning to take over and improve a project written by others using Codeigniter. Although I have used CI before, I wrote it completely according to my own wishes and did not follow some of the CI routines. For projects used by the public, it is best to follow the framework specifications, so it is better to summarize it to avoid making others laugh when they take over it in the future.

1. First is MVC

If you don’t know MVC yet, you should learn it as soon as possible. You will quickly realize the value of accessing data in the Model, performing business logic in the Controller, and writing HTML code in Views. You may wrinkle your forehead if you haven't programmed using this model before, but you should give yourself a chance to try it.

A rule of thumb is to put less stuff into the Controller and remember the DRY principle: don’t reinvent the wheel. When writing the same code in more than one place, you should try to write a library, helper, or model depending on its type. For example, the database connection class is used frequently, so it is made into a model (provided by the system).

Once you understand the essence of MVC, this will become a habit, and you will benefit a lot from MVC's concise code.

One principle is: leave complex operations to the Model. Controller is more like an architect. Model is hard work. View is the painter. The Controller only needs to throw things into the Model, and does not need to care whether the data is abnormal, and then returns a flag and corresponding data. In this way, the MVC architecture is reflected.

Model is actually like an electrical appliance such as a microwave oven. The simpler it is to use, the more people like it. (Put the food in - press start - ok, the rice is cooked.) The advantage of having fewer interfaces is that the Model upgrade code is optimized At that time, the coupling to the outside world was not high. Even if you write poorly internally, the interface is clean and easy to use.

2. Application and System paths

It is best to place the system and application folders outside the webroot. If index.php is placed under the /public_html/ path of the FTP server, you should try to place the System under the root directory /system. In this case, only Your PHP files can be accessed through index.php.

Don’t forget to modify the values ​​of $system_folder and $application_folder in the index.php file. The value of $system_folder should be relative to the index.php file, and the value of $application_folder should be relative to the system directory.

3. Error reporting and debugging

A common mistake is to forget to turn off PHP error and database error reporting, which is risky. In any public site, error_reporting should be set to 0, and can only be set to E_ERROR at most. The database setting db_debug should be set to false. Based on other security considerations, set error information not to be displayed ini_set('display_errors', 'Off');

As you code and debug, you should set error_reporting to E_ALL and address every note and warning before releasing your application.

A simple method is to set the value of db_debug to a constant MP_DB_DEBUG in the application/config/database.php file. When the website is running, set it as follows:

Copy code The code is as follows:

ini_set('display_errors', 'Off');
error_reporting(0);
define('MP_DB_DEBUG', false);

In coding and debugging set to:

Copy code The code is as follows:

ini_set('display_errors', 'On');
error_reporting(E_ALL);
define('MP_DB_DEBUG', true);

4. Security issues are very important

Before receiving any data to your program, whether it is POST data submitted by a form, COOKIE data, URI data, XML-RPC data, or data in the SERVER array, we recommend that you practice the following three steps:

Filter bad data.
Validate data to ensure correct type, length, size, etc. (Sometimes this step can also replace the first step)
Transform data before submitting it to your database.
Regarding SQL injection, XSS, and CSRF, you should first understand them before deciding whether to adopt methods to prevent them. You can refer to the security guidelines in the CI manual and the input and security categories. Perhaps the most important principle is to check all user input before submitting data to the database or file system.

SQL injection. Using Active Record that comes with CI can solve this problem.
XSS (cross-site scripting). By setting $config['global_xss_filtering'] = TRUE; to enable automatic filtering of cross-site scripting attacks in POST and COOKIE, it will consume some resources. It can also be used separately each time POST and COOKIE are processed, and the second parameter is set to TRUE, such as $this->input->post('some_data', TRUE); The form validation class also provides XSS filtering Options, such as $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
CSRF (cross-site request forgery). CI 2.0 will have built-in CSRF checking. Search Google for "CSRF tokens" to learn more about protecting form submissions and URL links. For Ajax applications, search for "double cookie submission" or "double submission cookie."
SPAM (spam and malicious registration). Prevent spam by protecting your email forms, comment forms, and various other free user-submitted data. An easy way to do this is to only allow one IP/User client to submit once a minute. One is better. The best way is to use Captcha. CI2 has a built-in CAPTCHA auxiliary function.

5. Database and ORM

CodeIgniter has a built-in library Active Record that can help you write query statements without using SQL statements. This is a good method if you are not very proficient in SQL statements or do not know how to prevent SQL injection.

When you need a more powerful tool, you can consider using Object Relational Mapper, which is the famous ORM. Unfortunately, CodeIgniter does not come with an ORM library, but there are some other good options.

Perhaps the most popular is DataMapper OverZealous Edition (DMZ), you can also use Doctrine (there is a tutorial here), another option RapidDataMapper is the author's own work.

6. Code Practice

Write concise code and understand your code, don’t just copy and paste other people’s code, and keep improving your coding skills. The Development Guidelines in the Handbook are a place to learn how to write better code.

1. DRY. Don't keep reinventing the wheel. Put reusable code where it belongs, such as libraries, helpers or models, not controllers. A rule of thumb: when you copy code, you may have already copied it a second time. It was put in the wrong place.

2. Caching. Caching is a great way to improve performance, especially by reducing database accesses. You can refer to web page caching and database caching, or search for other options on the forum. For example, MP_Cache is the author's own work.

3. HTTP headers. On the client side you can improve performance by causing the browser to cache the page by sending separate HTTP headers, and you also need to be aware of it to disable browser caching when you use AJAX.

An example of disabling caching:

Copy code The code is as follows:

$this->output->set_header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0", false);
$this->output->set_header("Pragma: no-cache");

An example of keeping cache for a long time (such as css, javascript):

Copy code The code is as follows:

$this->output->set_header('Cache-Control: private, pre-check=0, post-check=0, max-age=2592000');
$this->output->set_header('Expires: ' . gmstrftime("%a, %d %b %Y %H:%M:%S GMT", time() + 2592000));
$this->output->set_header('Last-Modified: ' . gmstrftime("%a, %d %b %Y %H:%M:%S GMT", time() - 20));

7. Template rendering does not have to call header and footer every time

Add the following content in the MY_Controller header and __construct function to set the default template information. SITE_NAME needs to be defined by yourself in application/config/constants.php:

Copy code The code is as follows:

class MY_Controller extends CI_Controller {
protected $_data; // Template value array
protected $_tplext; //Default template suffix
protected $_header; // Default header template
protected $_footer; //Default bottom template
public function __construct () {
       parent::__construct();
$this->_data['title'] = SITE_NAME;
        $this->_tplext = '.php';
$this->_header = 'templates/header';
        $this->_footer = 'templates/footer';
// Enable performance analysis in development mode
If (ENVIRONMENT === 'development') {
$this->output->enable_profiler(TRUE);
}
}
}

8. All classes do not have to inherit CI_Controller

The newly added controller no longer inherits CI_Controller, but instead inherits MY_Controller:

Copy code The code is as follows:

class Index extends MY_Controller {
public function __construct () {
       parent::__construct();
}
/**
* Front page
​*/
public function index () {
$this->_data['title'] = 'Home'; // If not specified, the default title will be used SITE_NAME
$this->_view('index/index');
}
}

Finally, let me add two more:

9. File structure of CodeIgniter

cache is used to store cache files. The codeigniter folder contains CI's base class CI_Base. In order to be compatible with php4 and php5, CI_Base has two versions. The php4 version of CI_Base inherits from CI_Loader. Libraries store most of the commonly used class libraries, the three most important classes: Model, View and Cotronller. Any mvc you write must inherit from the existing mvc class; helpers is a collection of functions (methods). Use To assist the convenient work of other modules. language is a language package to support multiple languages.

The application folder is used to store your application. CI has added some sub-files for you internally, including models, views, controllers, config, errors, hooks and libraries. The first three folders are used to create models, views and controllers. Most of your work should be to create your own MVC, and you can add configuration files to config and some objects and methods to libraries to assist your model and controller work. Hooks are also an extension of CI_Hooks. See the following chapters for details.

10. Working process of CodeIgniter

When there is an http request, such as http://www.google.com/blog/, first enter the CI boot file index.php. Next let's take a look at what is done in index.php.

index first sets the application folder name to application and the system folder name to system. Then it makes a series of strict judgments and converts them into unix-style server absolute file paths. Specifically, it defines two The more important constant, APPPATH, is the folder path of the application. According to analysis, this path can be at the same level as system: htdocs/application/, or it can be placed in the system folder as its subfolder: htdocs/system/ application/, but it is recommended to use the second method, which looks neater; BASEPATH, the basic file path of the website document, is probably htdoc/system/; in the end, the index boot file is introduced into codeigniter/codeigniter.php. Next we take a look at what is done in codeigniter.

codeigniter.php introduces three files at the beginning: Common.php, Compat.php and config/constants.php. Common contains some functions, including load_class for loading class libraries and log_message for recording logs. , and show_404, which introduces error pages, are several important functions; Compat mainly solves the function incompatibility problem in php4 and php5, while constants defines some constants for reading and writing file permissions.

Then codeigniter loads the first class library, Benchmark. One of the simplest applications of this class library is to calculate the time it takes from the beginning to the end of compilation of a web page, so you put a mark at the beginning of compilation. After the rendering is completed and a mark is added, the time spent can be calculated.

Then the second class library, Hooks, is loaded. Like Benchmark, this class library is under systemlibraries. The function of this class library is to provide you with an opportunity to perform other things before the program starts compiling. Hooks will Approximately 8 opportunities are provided for you to perform other tasks, see the User Guide for details. Here it imports the first hook.

Then load the Config, URI, Router, Output and other class libraries respectively. Then, check whether there is a cache_override hook. This hook allows you to schedule your own function to replace the _display_cache method of the Output class. If not, directly Call Output's _display_cache to check whether there is cache content. If there is, the cache will be output directly and exit; if not, the execution will continue.

After that, continue to load Input and Language. Note that the class library loaded before is a reference; then there is another important load, which is the loading of the CI_Base object. First, the version of php will be judged. If it is php4 version, Loader will be loaded first, and then Base4, because CI_Base in Base4 inherits from CI_Loader, but in Base5, CI_Base and CI_Loader have no inheritance relationship.

The next step is also the really critical step. This step starts by loading a Controller class. This is an instance, not a reference; then the http address is parsed through the Router to get the names of the controller and methods, and then look at the application controllers Whether there is such a controller and method, if not, an error will be reported; if there is, the judgment will start.

Summary

I will summarize this much first and will add more later. I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/945703.htmlTechArticleA summary of some excellent features of Codeigniter, codeigniter summary. Recently, I am planning to take over and improve a project written by others using Codeigniter, although it has been done before. I have used CI, but it is completely based on my own...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn