Codeigniter view & Model & controller

Source: Internet
Author: User
Tags php error php foreach codeigniter

Bytes --------------------------------------------------------------------------------------------------------

Load View

$ This-> load-> View ('home/name'); // you can use subfolders to store views. The default View File ends with '. php'.

 

Load multiple views

$ Data ['title'] = 'chenwei'; // Add dynamic data to the view

$ Data ['message'] = 'your message ';

$ This-> load-> View ('header', $ data); // when multiple views are loaded at a time, you only need to input data in the first view (header view displays title and content view displays message)

$ This-> load-> View ('menu ');

$ This-> load-> View ('content ');

$ This-> load-> View ('footer ');

Example of using objects:

$ DATA = new someclass ();

$ This-> load-> View ('blogview', $ data );

 

Variables in the View File

<Title> <? PHP echo $ title;?> </Title>

<Div> <? PHP echo $ message;?> </Div>

 

Create cycle

Class blog extends ci_controller {

Function Index ()

{

$ Data ['do _ list'] = array ('clean house', 'Call Ms', 'Run errands ');

$ Data ['title'] = 'My real title ';

$ Data ['heading'] = 'My real heading ';

      

$ This-> load-> View ('blogview', $ data );

}

}

 

<Title> <? PHP echo $ title;?> </Title>

<H1> <? PHP echo $ heading;?> </H1>

<Ul>

<? PHP foreach ($ todo_list as $ item):?>

<Li> <? PHP echo $ item;?> </LI>

<? PHP endforeach;?>

</Ul>

 

Get View content (assign a value to a variable)

$ Buffer = $ this-> load-> View ('blogview', $ data, true );

// The third optional parameter of the view function can change the behavior of the function. If the third parameter of view is set to true (Boolean), the function returns data. The default action of the view function is false, which sends data to the browser. If you want to return data, remember to assign it to a variable.

 

@ Blackeye poet: refer to the user manual to replace PHP syntax

PHP alternative syntax for view files =>

Open $ config ['rewrite _ short_tags'] in config/config. php. If your server does not support short tags, codeigniter will override all short tags.

Note: If you use this feature, if a PHP error occurs in your view file, the error message and row number cannot be accurately displayed. On the contrary, all errors are displayedEval ().

Normal echo format: <? PHP echo $ variable;?>

Use the alternative Syntax: <? = $ Variable?>

 

Alternative Control Structure

<Ul>

<? PHP foreach ($ todo_list as $ item):?>

<Li> <? = $ Item?> </LI>

<? PHP endforeach;?>

</Ul>

Note: There are no braces. Instead, the ending braces are replaced with endforeach. Each control structure listed above also has a similar close Syntax: endif, endfor, endforeach, and endwhile. Do not use semicolons (except the last one) after each structure, and use colons!

<? PHP if ($ username = 'chenwei'):?>

<H3> Hi chenwei.

<? PHP elseif ($ username = 'job'):?>

<H3> Hi Joe

<? PHP else:?>

<H3> Hi unknow user

<? PHP endif;?>

 

---------------------------------------- <Www. chenwei. ws> ----------------------------------------

 

Model files are stored in the application/models directory. Sub-directories can also be created to facilitate development and management of large projects.

Basic Model class

1. The first letter of the class name must be in upper case, and the other letters must be in lower case. Ensure that the basic model class ci_model is inherited, and the file name is in lower case of the model class name.

2. The model can be referenced in the controller.

For example, $ this-> load-> model ('user _ model'); or $ this-> load-> model ('home/user_model ');

Once a model is loaded, it can be used. By default, the model name is directly referenced as the object name.

For example, $ this-> user_model-> function ();

You can rename the object name by specifying the second parameter in the load model function.

For example, $ this-> load-> model ('user _ model', 'fubar ');

$ This-> fubar-> function ();

 

Automatic model Loading

If you need a specific model to play a role in the entire project, you can enable CI to automatically load it during initialization by adding the model to the automatic loading array of the application/config/autoload. php file.

 

Connect to database

When a model is loaded, it does not automatically connect to the database. The following methods allow you to connect to the database,

1. Connect to the database using the standard method

2. Set the third parameter to true to enable the model Loading Function to automatically connect to the database.

$ This-> load-> model ('user _ model', '', true );

3. manually set the third parameter to load your custom Database Configuration

$ Config ['hostname'] = 'localhost ';

$ Config ['username'] = 'root ';

$ Config ['Password'] = 'root ';

$ Config ['database'] = 'test ';

$ Config ['dbdriver '] = 'mysql ';

$ Config ['dbprefix'] = '';

$ Config ['pconnect '] = false;

$ Config ['db _ debug'] = true;

  

$ This-> load-> model ('user _ model', '', $ config );

// Note: the memory consumption is the same for automatic database connection and manual database connection.

 

Complete example:

Class user_model extends ci_model {

VaR $ Title = '';

VaR $ connect = '';

VaR $ DATA = '';

Function _ construct ()

{

Parent: :__ construct ();

}

Function get_last_ten_entries ()

{

$ Query = $ this-> DB-> get ('entries', 10 );

Return $ query-> result ();

}

Function insert_entry ()

{

$ This-> Title = $ this-> input-> post ('title'); // receives data submitted by post, using the input class

$ This-> content = $ this-> input-> post ('content ');

$ This-> date = Time ();

 

$ This-> DB-> insert ('entries', $ this );

}

Function update_entry ()

{

$ This-> Title = $ this-> input-> post ('title ');

$ This-> content = $ this-> input-> post ('content ');

$ This-> date = Time ();

 

$ This-> DB-> Update ('entries', $ this, array ('id' => $ this-> input-> post ('id ')));

}

}

// The above function is an active record database function.

 

Bytes -----------------------------------------------------------------------------------------------------

 

Controller files are generally stored in the application/controllers/folder:

Default URL routing configuration $ config ['uri _ Protocol'] = 'auto'; // pathinfo mode by default. Optional.

 

Note: The class name must start with an upper-case letter and the lower-case letter must be invalid.

Basic controller class

Class blog extends ci_controller {

Public Function _ construct ()

{

Parent: :__ construct ();

// Constructor does not return values, but can be used to set some default functions. Make sure that your controller extends from the parent controller class so that it can inherit all its methods.

}

Public Function Index ()

{

Echo 'Hello world! ';

}

Public Function comments ()

{

$ This-> load-> View ('comment ');

}

}

// Use example.com/index.php/blog/comments to access the comments Method

 

Define default Controller

$ Route ['default _ controller'] = 'blog 'in application/config/routes. php ';

 

Put controllers in subfolders

Create a new directory under the application/controllers directory and add it to the Controller. Note: If you want to use the functions in a sub-folder, make sure that the first segment of the URI is used to describe the folder. Application/index. php/home/blog/comments/123

 

Private method:

Private function _ test ()

{

Return $ variable = 'aaa'; // even if no modifier private is added, the method name is prefixed with an underscore (_) in front of the method name, which is a private method and cannot be accessed through a URL.

}

 

Method Name retained:

The Controller class name cannot be index, for example, class index extends ci_controller {}. Because index is the default CI method name, it is included in reserved words. For details, refer to reserved words.

 

Re-define the method call rules:

_ Remap ();

 

Processing output:

_ Output (); For more information, see output class.

Bytes ----------------------------------------------------------------------------------------------

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.