Introduction to the CI framework: Models and auxiliary functions

Source: Internet
Author: User
If you want to add some new functions to the original helper function file, such as adding one or two new methods or modifying one method; it is not worth rewriting your auxiliary function file. In this case, it is best to "extend" the existing auxiliary function file. Happy new year! Unconsciously, we arrived in 2013, and I wish you all the best in the new year ~~


Today we are going to learn models and auxiliary functions in CI.



[Content of this lecture]

I. model;

Previously, we introduced the C and V layers in the MVC mode, but the M layer has not been discussed yet. Now let's talk about it.


What is a model? How to create a simple model? How to load a model?


II. auxiliary functions.

When we need to complete some specific tasks, helper functions will come in handy. I still remember what CI can do for us in the first lecture. one of the advantages of CI is to reduce the amount of code, so the CI auxiliary function can help us do this.




[Details]

1. model.
(1) What is a model?


The model is optional for those with traditional MVC methods. For example, M layer is not used in some of the examples we mentioned earlier. it is because we have not involved operations with the database yet. once database operations are involved, we need to use M layer, because the model (M) is specifically used to deal with databases.



(2) how to create a model?


In fact, the model is a PHP class that contains methods such as adding, deleting, updating, and statistic data. let's create a simple look. the code is as follows:
Copy code
  1. Class User_model extends CI_Model {
  2. Function _ construct ()
  3. {
  4. Parent: :__ construct ();
  5. }
  6. // Perform the data retrieval operation
  7. Function get ()
  8. {
  9. // Code omitted ......
  10. }
  11. // Perform the add data operation
  12. Function insert ()
  13. {
  14. // Code omitted ......
  15. }
  16. // Update data
  17. Function update ()
  18. {
  19. // Code omitted ......
  20. }
  21. // Delete data
  22. Function delete ()
  23. {
  24. // Code omitted ......
  25. }
  26. }

Pay attention to the following points:


A. The created model class file should be placed in the application/models/folder, and the file name should be in lowercase format of the model class name. For example, in the above example, the file name should be user_model.php;


B. first letter of the class name RequiredUppercase; lowercase for other letters;


C. make sure that your class inherits the basic model class (CI_Model ).


How can I use this model file after it is created?


(3) load the model.


The model we wrote is loaded and referenced by the controller. The load model has two methods in CI:


One is manual loading. if we want to load the model class above, it can be easily loaded in the method in the controller, just like this:

Copy code
  1. $ This-> load-> model ('User _ Model ');


The above are usually loaded in the controller's constructor. after all, it only needs to be manually loaded once.



The other is automatic loading. find and open application/config/autoload. php file, and then add this model to the automatically loaded array, as long as you set $ autoload ['model'] = array ();:

Copy code
  1. $ Autoload ['model'] = array ('User _ Model ');
After loading the model, we can use it:

Copy code
  1. $ This-> User_model-> add ();
  2. $ This-> User_model-> insert ();



Next, Jun Ge will take you to a complete example to make the previous content consistent and review it.


Because we will involve database operations, we must first configure the database and open Application/config/database. phpFile, set some parameter values for connecting to the database, as follows:
Copy code
  1. $ Db ['default'] ['hostname'] = 'localhost ';
  2. $ Db ['default'] ['username'] = 'Your database hostname ';
  3. $ Db ['default'] ['password'] = 'Your database password ';
  4. $ Db ['default'] ['dbdriver '] = 'mysql ';
  5. $ Db ['default'] ['database'] = 'Your database name ';


The above just sets a part of the parameters and would like to learn more you can browse CI China's Chinese manual, http://codeigniter.org.cn/user_guide/database/configuration.html.


Create a data table named "user". the table structure is as follows:
Copy code
  1. Create table user (
  2. Id int (11) auto_increment primary key not null,
  3. Name varchar (30) not null default '',
  4. Nickname varchar (50) not null default '',
  5. Sex varchar (20) not null default 'male ',
  6. Age int (11) not null default 0
  7. );

Insert a data record as follows:

Copy code
  1. Insert into user values (null, 'jayjun', 'Pork ribs go', 'male', '26 ');
  2. Insert into user values (null, 'Hot go', 'should be male', 'male', '27 ');



Next we will write a user model named user_model.php. the code is as follows:
Copy code
  1. Class User_model extends CI_Model {
  2. // Obtain user information
  3. Public function get ()
  4. {
  5. $ Data = '';
  6. // Select part of the SQL statement. all fields in the user table are queried here.
  7. $ This-> db-> select ("*");
  8. // Run the select query statement and return the result set to $ data
  9. $ Data = $ this-> db-> get ("user ");
  10. Return $ data;
  11. }
  12. }
  13. ?>
Then write the controller and name it user. php. the code is as follows:

Copy code
  1. Class User extends CI_Controller {
  2. // Constructor
  3. Function _ construct ()
  4. {
  5. Parent: :__ construct ();
  6. // Load the user model
  7. $ This-> load-> model ("User_model ");
  8. }
  9. // Display the user information List
  10. Public function index ()
  11. {
  12. // Call the get method in the user model to return the result set to $ query
  13. $ Query = $ this-> User_model-> get ();
  14. // Return the result set as an associated array
  15. $ Data ['userlist'] = $ query-> result_array ();
  16. $ This-> load-> view ('User _ INDEX', $ data );
  17. }
  18. }
  19. ?>
Finally, we start to write The View. the code is as follows:

Copy code
  1. A simple example with model
  2. ID number Name Nickname Gender Age



Now, open the browser and enter http: // localhost/ci_demo/index. php/user/index to access the user list!

If you do not see an error, the following result is displayed:

Image: 97b82afbjw1e0gkya33j3j.jpg





2. auxiliary functions.

Speaking of functions, this really has to say that functions are a good thing. they can help us solve many complicated problems. as we all know, they are also invented for reuse, it can reduce the amount of our code and improve our coding efficiency. we often cannot leave it alone. The most important thing is that CI itself provides us with a series of auxiliary function files with different functions. June cut a CI Chinese manual, as shown in:







We can see that CI provides up to 21 auxiliary function files. For example, there is an Array helper function File (Array Helpers) used to process Array operations, and a Form helper function File (Form Helpers) that helps you create a Form) and the URL helper function File (URL Helpers) that helps us create links. If this does not meet your needs, you can easily "expand" these function files or use custom function files.



Helper function files are generally stored in the system/helpers or application/helpers folder. CI will first find the corresponding auxiliary function file in application/helpers. if the directory does not exist or there is no corresponding auxiliary function file in the directory, CI will load the auxiliary function file under system/helpers.

(1) load auxiliary functions.

CI does not load the auxiliary function file by default, so if you want to use the auxiliary function, you must first load it. Once loaded, helper functions are available globally. you can use them in controllers and views. We load the auxiliary function file like this:
Copy code
  1. $ This-> load-> helper ('helper function file name, without the _ helper and. php suffixes ');

For example, you want to load the array auxiliary function file, just like this:
Copy code
  1. $ This-> load-> helper ("array ");


If you want to load multiple helper functions at a time, you can do this:
Copy code
  1. $ This-> load-> helper (array ('helper1', 'helper2', 'helper3 '));



(2) use helper functions.


For example, after loading a URL helper function file, we can use a function in it, such as anchor (), which has three optional parameters:
Copy code
  1. Anchor (uri segments, text, attributes );


The first parameter contains the parameters you want to append to the URL;


The second parameter is the name of the link you want to connect;


The third parameter contains a set of attributes you want to attach to the link.


For example:
Copy code
  1. Echo anchor ('jayjun/feadback', 'feedback & communication', 'title = "Feedback & communication "');
  2. ?>
Equivalent:
Copy code
  1. Feedback and communication


(3) "extended" auxiliary functions.


If you want to add some new functions to the original helper function file, such as adding one or two new methods or modifying one method; it is not worth rewriting your auxiliary function file. In this case, it is best to "extend" the existing auxiliary function file.



For example, when writing PHPer's search function, June needs to remove the two-dimensional array repeated value of the search results (for details, see: http://phpersite.sinaapp.com/index.php/jayjun/doc/start/2/cid/28/aid/62.html ), however, the original array helper function file does not support functions. in this case, you need to customize a function to help us deal with it. that is to say, "extended" an array helper function file. in this case, you should create a file: application/helpers/MY_array_helper.php: write the custom function to use it in the controller.



Next, we will learn how to use the class library in CI and how to create a class library of our own.

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.