YiiFramework introduction knowledge point summary (Graphic tutorial) _ php instance

Source: Internet
Author: User
This article mainly introduces the YiiFramework entry point, and analyzes the creation steps and precautions of YiiFramework in combination with the text form. For more information, see the following section. We will share this with you for your reference. The details are as follows:

Create Yii application skeleton

Web is the website root directory
Yiic webapp/web/demo

When creating models and CURD using GII, note that

1. Model Generator operation

Even if a Table prefix is available, the full Name of the Table, including the Table prefix, must be entered in Table Name. For example:

2. Crud Generator operation

In this interface, enter the Model name in model Class. Uppercase letters. You can also refer to the file name generated by model generator in the proctected/models directory when generating the model. For example:

If you generate a CURD controller for the news, newstype, and statustype tables, in Model Generator, enter News, newsType, and StatusType in Model Class. The case is the same as the name of the created file. Neither NEWS nor NeWs can be written.

Precautions for creating a module

Create a Module through GII. The Module ID is generally in lower case. In any case, the ID entered here determines the configuration in the main. php configuration file. As follows:

'Modules' => array ('admin' => array (// The admin of this line is the Module ID. 'Class' => 'application. modules. admin. adminModule ', // It doesn't matter if admin is in upper or lower case in windows OS, but it is better to be consistent with the actual directory. ),),

Routing

System indicates the framework directory of the yii framework
Application indicates the protected directory under the created application (such as d: \ wwwroot \ blog.
Application. modules. Admin. AdminModule
Indicates AdminModules under the Admin directory under the application directory (for example, d: \ wwwroot \ blog \ protected. PHP file (actually pointing to the class name of the file)
System. db .*
All files in the db directory under the framework directory under the YII framework.

AccessRules description in the Controller

/*** Specifies the access control rules. * This method is used by the 'accesscontrol' filter. * @ return array access control rules */public function accessRules () {return array ('allow ', // allow all users to perform 'index' and 'view' actions 'actions' => array ('index', 'view '), // indicates that any user can access index and view Methods 'users' => array ('*'), // indicates any user), array ('allow ', // allow authenticated user to perform 'create' and 'update' actions 'actions' => array ('create', 'update '), // indicates that only authenticated users can operate the create and update Methods 'users' => array ('@'), // indicates authenticated users), array ('allow ', // allow admin user to perform 'admin' and 'delete' actions 'actions' => array ('admin', 'delete '), // indicates that only the user admin can access the admin and delete Methods 'users' => array ('admin'), // indicates the specified user. Here, the user is admin ), array ('deny', // deny all users 'users' => array ('*'),),);}

See the above Code comments.

User: represents the user session information. For details, refer to API: CWebUser.
CWebUser represents the persistent state of a Web application.
CWebUser is an application component whose ID is user. Therefore, you can useYii: app ()-> userAccess user status

Public function beforeSave () {if (parent: beforeSave () {if ($ this-> isNewRecord) {$ this-> password = md5 ($ this-> password ); $ this-> create_user_id = Yii: app ()-> user-> id; // At the beginning, User: model ()-> user-> id; (error) // $ this-> user-> id; (error) $ this-> create_time = date ('Y-m-d H: I: s ');} else {$ this-> update_user_id = Yii: app ()-> user-> id; $ this-> update_time = date ('Y-m-d H: I: s ');} return true;} else {return false ;}}

Getter method or/and setter Method

<?php/** * UserIdentity represents the data needed to identity a user. * It contains the authentication method that checks if the provided * data can identity the user. */class UserIdentity extends CUserIdentity{  /**   * Authenticates a user.   * The example implementation makes sure if the username and password   * are both 'demo'.   * In practical applications, this should be changed to authenticate   * against some persistent user identity storage (e.g. database).   * @return boolean whether authentication succeeds.   */  private $_id;  public function authenticate()  {    $username=strtolower($this->username);    $user=User::model()->find('LOWER(username)=?',array($username));    if($user===null)    {      $this->errorCode=self::ERROR_USERNAME_INVALID;    }    else    {      //if(!User::model()->validatePassword($this->password))      if(!$user->validatePassword($this->password))      {        $this->errorCode=self::ERROR_PASSWORD_INVALID;      }      else      {        $this->_id=$user->id;        $this->username=$user->username;        $this->errorCode=self::ERROR_NONE;      }    }    return $this->errorCode===self::ERROR_NONE;  }  public function getId()  {    return $this->_id;  }}

Model/User. php

Public function beforeSave () {if (parent: beforeSave () {if ($ this-> isNewRecord) {$ this-> password = md5 ($ this-> password ); $ this-> create_user_id = Yii: app ()-> user-> id; // ===. Get the login account ID $ this-> create_time = date ('Y-m-d H: I: s');} else {$ this-> update_user_id = Yii :: app ()-> user-> id; $ this-> update_time = date ('Y-m-d H: I: s');} return true ;} else {return false ;}}

More information:

/* Because CComponent is the top parent class of post, add the getUrl method .... CComponent is the base class of all component classes. CComponent implements the protocol for defining and using attributes and events. The property is defined by the getter method or/and setter method. Access attributes are like accessing common object variables. The getter or setter method corresponding to the read or write attribute will be called, for example, $ a = $ component-> text; // equivalent to $ a = $ component-> getText (); $ component-> text = 'abc'; // equivalent to $ component-> setText ('abc'); the format of the getter and setter methods is as follows // getter, defines a readable property 'text' public function getText (){...} // setter, defines a writable property 'text' with $ value to be set to the propertypublic function setText ($ value ){...} */public function getUrl () {return Yii: app ()-> createUrl ('Post/view', array ('id' => $ this-> id, 'title' = >$ this-> title ,));}

Rules method in the Model

/** Rules method: Specifies the validation rules for model attributes * when the model instance calls the validate or save method, the * verification must be performed one by one. Such as id and Author id, which are set by code or database, do not appear in rules. * // *** @ Return array validation rules for model attributes. */public function rules () {// NOTE: you shoshould only define rules for those attributes that/will receive user inputs. return array ('news _ title, news_content ', 'required'), array ('news _ title', 'length', 'max' => 128 ), array ('news _ content', 'length', 'max '=> 8000), array ('author _ name, type_id, status_id, create_time, update_time, create_user_id, update_user_id ', 'Safe '), // The following rule is used by search (). // Please remove those attributes that shocould not be searched. array ('Id, news_title, news_content, author_name, type_id, status_id, create_time, update_time, create_user_id, update_user_id ', 'safe ', 'on' => 'search '),);}

Note:

1. The verification field must be an attribute entered by the user. It is not the content entered by the user and does not require verification.
2. Operation fields in the database (even those generated by the system, such as the creation time and update time)-In the yii_computer source code provided by boyLee, these attributes generated by the system are not placed in safe. See the following code ).For data not provided by forms, all data that is not verified in the rules method must be added to safe. Otherwise, data cannot be written to the database..

About the rules method in the News. php model of yii_computer

/** * @return array validation rules for model attributes. */public function rules(){  // NOTE: you should only define rules for those attributes that  // will receive user inputs.  return array(    array('news_title, news_content', 'required'),    array('news_title', 'length', 'max'=>128, 'encoding'=>'utf-8'),    array('news_content', 'length', 'max'=>8000, 'encoding'=>'utf-8'),    array('author_name', 'length', 'max'=>10, 'encoding'=>'utf-8'),    array('status_id, type_id', 'safe'),    // The following rule is used by search().    // Please remove those attributes that should not be searched.    array('id, news_title, news_content, author_name, type_id, status_id', 'safe', 'on'=>'search'),  );}

Three methods for displaying dynamic content in a view

1. directly implement PHP code in the View File. For example, to display the current time, in the View:

The Code is as follows:

<? Php echo date ("Y-m-d H: I: s");?>


2. display the content in the Controller and pass it to the view using the second render parameter.

The Controller method includes:

$theTime=date("Y-m-d H:i:s");$this->render('helloWorld',array('time'=>$theTime));

View File:

The Code is as follows:

<? Php echo $ time;?>


The second parameter of the called render () method is an array (array type). The render () method extracts the values in the array and provides them to the View Script. The keys in the array (key value) the variable name provided to the View Script. In this example, if the key value of the array is time and the value is $ theTime, the variable name $ time is extracted for the View Script. This is a way to pass the Controller data to the view.

3. the view and the controller are very close, so $ this in the View File refers to the Controller that renders the view. Modify the previous example to define the public attributes of a class in the controller, instead of local variables. The value is the current date and time. Then, access the attributes of this class through $ this in the view.

View naming conventions

View File Name, which must be the same as ActionID. But remember, this is just a recommendation naming convention. In fact, the View File name does not have to be the same as the ActionID. You only need to pass the file name to render () as the first parameter.

DB Problems

$Prerfp = Prerfp::model()->findAll(  array(    'limit'=>'5',    'order'=>'releasetime desc'  ));

$ Model = Finishrfp: model ()-> findAll (array ('select' => 'companyname, title, releasetime', 'order' => 'releasetime desc ', 'limit' => 10); foreach ($ model as $ val) {$ noticeArr [] = "in ". $ val-> title. "bidding ,". $ val-> companyname. "winning. ";}

$model = Cgnotice::model()->findAll (  array(    'select' => 'status,content,updatetime',    'condition'=> 'status = :status ',    'params' => array(':status'=>0),    'order'=>'updatetime desc',    'limit' => 10  ));foreach($model as $val){  $noticeArr[] = $val->content;}

$user=User::model()->find('LOWER(username)=?',array($username));

$noticetype = Dictionary::model()->find(array( 'condition' => '`type` = "noticetype"'));

// Find the row with postID = 10 $ post = Post: model ()-> find ('postid =: postid', array (': postid' => 10 ));

You can also use $ condition to specify more complex query conditions. Without a string, we can make $ condition an instance of CDbCriteria, which allows us to specify conditions not limited to WHERE. For example:

$ Criteria = new CDbCriteria; $ criteria-> select = 'title'; // select only the 'title' column $ criteria-> condition = 'postid =: postid '; $ criteria-> params = array (': postid' => 10); $ post = Post: model ()-> find ($ criteria ); // $ params no longer required

Note: When CDbCriteria is used as the query condition, the $ params parameter is no longer needed because it can be specified in CDbCriteria, as shown above.

One alternative to CDbCriteria is to pass an array to the find method. The keys and values of the array correspond to the attribute names and values of the standard (criterion). The preceding example can be rewritten as follows:

$post=Post::model()->find(array( 'select'=>'title', 'condition'=>'postID=:postID', 'params'=>array(':postID'=>10),));

Others

1. Links

The Code is as follows:

<? Php echo CHtml: link (Controller: utf8_substr ($ val-> title,), array ('prerfp/details ', 'id' => $ val-> rfpid), array ('target' => '_ blank');?>

For more information, see the link () method of CHtml.

The Code is as follows:

Title;?> "Href =" <? Php echo $ this-> createUrl ('prerfp/details', array ('id' => $ val-> rfpid);?> "> <? Php echo Controller: utf8_substr ($ val-> title, 0, 26);?>


For details, refer to the API documentation: CController's createUrl () method.

The above two connections have the same effect.

Component inclusion

Example:

The following code is available at the bottom of the View:

The Code is as follows:

<? Php $ this-> widget ('notice');?>

Open the Notice. php file under protected/components. The content is as follows:

<?phpYii::import('zii.widgets.CPortlet');class Banner extends CPortlet{  protected function renderContent()  {    $this->render('banner');  }}

The rendered view banner is under the protected/components/views directory.

For more information, see the API. Keyword:CPortlet

Obtain the current host

Yii::app()->request->getServerName();//and$_SERVER['HTTP_HOST'];$url = 'http://'.Yii::app()->request->getServerName(); $url .= CController::createUrl('user/activateEmail', array('emailActivationKey'=>$activationKey));echo $url;

How to add ckeditor extension when publishing news

$this->widget('application.extensions.editor.CKkceditor',array(  "model"=>$model,        # Data-Model  "attribute"=>'news_content',     # Attribute in the Data-Model  "height"=>'300px',  "width"=>'80%',"filespath"=>Yii::app()->basePath."/../up/","filesurl"=>Yii::app()->baseUrl."/up/", );

Echo Yii: app ()-> basePath

If the project directory is in the Directory d: \ wwwroot \ blog. The above value is d: \ wwwroot \ blog \ protected. Note that there is no backslash at the end of the path.

Echo Yii: app ()-> baseUrl;

If the project directory is in the Directory d: \ wwwroot \ blog. The above value is/blog. Note that there is no backslash at the end of the path.

(D: \ wwwroot is the website root directory ),Note the two differences above. One is basePath and the other is baseUrl.

Others (not necessarily true)

In the view corresponding to Controller A, call the method in model B by using the method name () in model B: model ()-> model B ();

APIS to be mastered in the Early Stage
CHtml

I hope this article will help you design PHP programs based on the Yii framework.

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.