7-point CI framework development skills

Source: Internet
Author: User
If you do not know what ci is, read this article to describe a simple CI framework instance and its running mechanism. The following are the advanced development skills of the CI framework! The php Tutorial is as follows: (1) automatically load the model models and you do not need to inherit the model class anymore.

If you do not know what ci is, read this article to describe a simple CI framework instance and its running mechanism.

The following are the advanced development skills of the CI framework!

The php Tutorial is as follows:

(1) automatically load the model models

You do not need to inherit the model class anymore. You can add a php5-style autolader function to add the code to system/application/config. php:


 

If you are also interested in using this technique to controller, you only need to add the following code to replace the above code.


 

Whenever you try to use an undefined class, the _ autoload function will be called and it will load the class file.

 

(2) prevent model-controller name conflicts

The php file name is also very important. the following php code:

Class Post extends Model {

//...

}

Now you cannot have a url like this:

Http://www.phpddt.com/post/display/13

This is because you also need a controller named post. if you create such a class, it will cause a fatal error.

But with this technique, everything is possible. The url controller looks like this:

// Application/controllers/post. php

Class Post_controller extends Controller {

//...

}

Tips:

To avoid this problem, most people generally add the '_ model' suffix to the model name (for example, Post_model ).

Model objects are created and referenced in all applications, so it is boring to keep up with '_ model' after all model names.

I think the best way is to add a suffix to the controller, because the controller name is almost never referenced in the code.

First, we need to inherit the Router class. Create a file: "application/libraries/MY_Router.php"


class MY_Router extends CI_Router {      var $suffix = '_controller';      function MY_Router() {          parent::CI_Router();      }      function set_class($class) {          $this->class = $class . $this->suffix;      }      function controller_name() {          if (strstr($this->class, $this->suffix)) {              return str_replace($this->suffix, '', $this->class);          }          else {              return $this->class;          }      }  }  

Edit "system/codeigniter/CodeIgniter. php" row 153rd

If (! File_exists (APPPATH. 'controllers/'. $ RTR-> fetch_directory (). $ RTR-> controller_name (). EXT ))

Then there are 158th rows

Include (APPPATH. 'controllers/'. $ RTR-> fetch_directory (). $ RTR-> controller_name (). EXT );

Edit the 323rd line of "system/libraries/Profiler. php ".

 

$ Output. = "". $ this-> CI-> router-> controller_name (). "/". $ this-> CI-> router-> fetch_method (). "";

 

Success. To use this technique, you must remember to put the '_ controller' suffix behind the name of your controller class, not your controller file name.

(3) form verification "unique value" (for example, registering username email)

Ci has a perfect form verification class. However, this verification is insufficient. for example, when most users register a user name, you need to verify that the user name is not in use, or whether the mailbox exists in the system.

With this technique, you can easily add this validation rule to your form submission.

Note that the last section "unique [User. username]. "This new validation rule is called" unique "and contains a box in this brackets, which are" tablename. filedname ". therefore, it will check that the "username" column of the "user" data table of the database determines that the submitted value does not exist in the database.

Similarly, you can use this rule to verify the same email address.

$ This-> form_validation-> set_rules ('email ', 'e-mail ',

'Required | valid_email | unique [User. email] ');

Your application gets an error message.

It is not so much a skill as an extension. Even so, we will add a core ci class library and improve it.

Create the "application/libraries/MY_Form_validation.php" file

 

Now you can use this "unique" verification rule.

 

(4) run codeigniter from the command line

This is a cool way to execute CI

Create a "cli. php" file in the ci root directory

If (isset ($ _ SERVER ['remote _ ADDR ']) {

Die ('command Line Only! ');

}

Set_time_limit (0 );

$ _ SERVER ['path _ info'] = $ _ SERVER ['request _ URI '] = $ argv [1];

Require dirname (_ FILE _). '/index. php ';


class MY_Form_validation extends CI_Form_validation {      function unique($value, $params) {          $CI =& get_instance();          $CI->load->database();          $CI->form_validation->set_message('unique',              'The %s is already being used.');          list($table, $field) = explode(".", $params, 2);          $query = $CI->db->select($field)->from($table)->where($field, $value)->limit(1)->get();          if ($query->row()) {              return false;          } else {              return true;          }      }  }

If you want to use this code in linux and want it to be automatically executed, you can add the following code in the first line of the cli. php file.

#! /Usr/bin/php

If you need a controller that can only be used in the command line, you can prevent the web from calling the controller constructor.

 

 

(5) add Doctrine orm to codeigniter

Doctine is a popular php relational object ing (orm ). After you add it to ci, you will have a more powerful model layer.

 

Tips:

In fact, installing Doctrine is not that difficult, just like installing a plug-in. Once the installation is successful, your model class will inherit the Doctrine base class, rather than the model class of ci. This will completely change the working method of the model layer. The object you create will have persistent database connections and other object database relationships.


class Hello extends Controller {      function __construct() {          if (isset($_SERVER['REMOTE_ADDR'])) {              die('Command Line Only!');          }          parent::Controller();      }      // ...  }

Follow these steps:

1. create a folder: application/plugins

2. create a folder: application/plugins/doctrine

3. download an object (version 1.2)

4. copy the "lib" folder from Doctrine to "application/plugins/doctrine"

5. create "application/plugins/doctrine_pi.php"

 

// System/application/plugins/doctrine_pi.php

 

// Load Doctrine library

Require_once APPPATH. '/plugins/doctrine/lib/Doctrine. php ';

 

// Load database configuration from CodeIgniter

Require_once APPPATH. '/config/database. php ';

 

// This will allow Doctrine to load Model classes automatically

Spl_autoload_register (array ('doctrine', 'autoload '));

 

// We load our database connections into Doctrine_Manager

// This loop allows us to use multiple connections later on

Foreach ($ db as $ connection_name => $ db_values ){

 

// First we must convert to dsn format

$ Dsn = $ db [$ connection_name] ['dbdriver '].

': //'. $ Db [$ connection_name] ['username'].

':'. $ Db [$ connection_name] ['password'].

'@'. $ Db [$ connection_name] ['hostname'].

'/'. $ Db [$ connection_name] ['database'];

 

Doctrine_Manager: connection ($ dsn, $ connection_name );

}

 

// CodeIgniter's Model class needs to be loaded

Require_once BASEPATH. '/libraries/Model. php ';

 

// Telling Doctrine where our models are located

Doctrine: loadModels (APPPATH. '/models ');

 

Then, edit 'application/config/autoload. php' to automatically load the Doctrine plug-in.

$ Autoload ['plugin'] = array ('doctrine ');

 

Make sure that you have configured the application/config/database. php database ,"

 

 

(6) run multiple sites

Objectives:

This technique will make it possible to install a codeigniter to run multiple sites. Each site has its own application folder, but they share the same system folder.

 

Tips:

Install ci anywhere on the server. Then, extract the application folder from the system folder. Put it outside. see the picture above.

Copy the index. php file to the following directory of each site (application_site1 and application_site2 in the figure)

Edit it:

In row 26th, the complete path of the system folder is provided.

$ System_folder = dirname (_ FILE _). '../codeigniter/system ';

 

In row 3, the article path of the application folder is provided.

$ Application_folder = dirname (_ FILE _). '../application_site1 ';

Now you can use an independent application folder to create different sites, but share the same system folder.

There is a similar operation in the ci user manual.

 

(7) allow all types of files to be uploaded

Goal: when uploading files, you will often encounter file type errors!

$ This-> load-> library ('upload'); $ this-> upload-> set_allowed_types ('jpg | jpeg | gif | png | zip ');

If you do not specify a specific Upload type, you will get an error message from ci "Youhave not specified any allowed file types ."

All. by default, all files cannot be uploaded. We need to make some small changes to deal with this restriction. We set "*" to run all types of file uploads.

$ This-> load-> library ('upload'); $ this-> upload-> set_allowed_types ('*');

 

Tips:

We need to modify the Upload file class.

Create a File: application/librarys/My_upload.php


class MY_Upload extends CI_Upload {      function is_allowed_filetype() {          if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))          {              $this->set_error('upload_no_file_types');              return FALSE;          }          if (in_array("*", $this->allowed_types))          {              return TRUE;          }          $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');          foreach ($this->allowed_types as $val)          {              $mime = $this->mimes_types(strtolower($val));              // Images get some additional checks              if (in_array($val, $image_types))              {                  if (getimagesize($this->file_temp) === FALSE)                  {                      return FALSE;                  }              }              if (is_array($mime))              {                  if (in_array($this->file_type, $mime, TRUE))                  {                      return TRUE;                  }              }              else              {                  if ($mime == $this->file_type)                  {                      return TRUE;                  }              }          }          return FALSE;      }  }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.