This article summarizes the yiiframework getting started knowledge point. Share to everyone for your reference, as follows:
Create a YII application skeleton
Web as Web site root directory
YIIC Webapp/web/demo
When creating model and curd through the GII, it is important to note
1. Model Generator operation
Even in the case of a table prefix, the full name of the table is filled in table name, which includes the table prefix. Such as:
2. Crud Generator operation
In this interface, the model class is filled in with the model name. Capitalize the first letter. You can also refer to the file name generated by the model generator in the Proctected/models directory when the model is generated. Such as:
If curd controller is generated for news, Newstype, Statustype, then in Model generator, enter: News, Newstype, Statustype in model class. The case is the same as the case of the file name that was created. If you write news or news, you can't.
Considerations for creating Modules
Module IDs are generally lowercase in the modules created through the GII. In any case, the ID that is filled in here determines the configuration in the main.php configuration file. As follows:
' Modules ' =>array ( ' admin ' =>array (//) the admin for this line is the module ID. The module ID that was filled in when you created the module is uppercase and lowercase ' class ' = ' application.modules.admin.AdminModule ',//the admin here does not matter in the case of Windows OS , but it's best to match the actual directory. ),),
Routing
System represents the framework directory of the YII framework
Application represents the protected directory under the created app (such as D:\wwwroot\blog).
Application.modules.Admin.AdminModule
Represents the adminmodules.php file under the Admin directory in the directory of the application directory (for example: d:\wwwroot\blog\protected) under the Modules directory (actually pointing to the name of the class of the file)
system.db.*
Represents all files under the framework directory under the YII framework under the DB directory.
Accessrules instructions in the controller
/** * Specifies the access control rules. * This method was used by the ' AccessControl ' filter. * @return Array access control rules */public function Accessrules () { return Array ( "Allow",//Allow all US ERs to perform ' index ' and ' view ' actions ' actions ' =>array (' index ', ' view '),//means any user can access index, view method ' Users ' =>array (' * '),//represents 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, Update method ' users ' =>array (' @ '),// Represents the authenticated user ), array (' Allow ',//Allow Admin user to perform ' admin ' and ' delete ' actions ' actions ' =>array (' Admin ', ' delete '),//means only user admin can access Admin, delete method ' users ' =>array (' admin '),//For specified user, here refers to User: admin ), Array (' Deny ',//Deny all users ' users ' =>array (' * '),) ;}
See the code comment above.
User:represents the user session information. Read more Api:cwebuser
Cwebuser represents a persistent state for a Web application.
Cwebuser as an application component with ID of user. Therefore, you can access user status from anywhere via Yii::app ()->user
Public Function BeforeSave () { if (Parent::beforesave ()) { if ($this->isnewrecord) { $this- >PASSWORD=MD5 ($this->password); $this->create_user_id=yii::app ()->user->id;//first wrote, 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 is 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;//==== mainly for this sentence. Get the ID of the login account $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 about:
/* Because Ccomponent is the top-most parent of the post, add the Geturl method .... The following is a description: Ccomponent is the base class for all component classes. Ccomponent implements the protocol that defines, uses properties, and events. Properties are defined by getter methods or/and setter methods. Accessing a property is like accessing a normal object variable. The read or write property will call the getter or setter method that should be used for example: $a = $component->text; Equivalent to $a = $component->gettext (); $component->text= ' abc '; Equivalent to $component->settext (' abc '); Getter and setter methods are formatted as follows//getter, defines a readable property ' text ' public function GetText () {...} Setter, defines a writable property ' text ' with $value to is set to the PropertyPublic function SetText ($value) {...} */public function GetUrl () { return Yii::app ()->createurl (' Post/view ', array ( ' id ' = = $this->id, ' title ' = = $this->title, ));}
Rules methods in the model
/* Rules method: Specifies the validation rule for model properties * The property that must be entered by the user when the model instance calls validate or the Save method is executed one at a time. such as ID, author ID, etc. are set by code or database does not appear in the rules. *//** * @return Array validation rules for model attributes. */public function Rules () { //note:you should only define rules for those attributes that //would receive user in Puts. Return Array ( 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 this should 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 ') ;
Description
1. Verify that the field must be a user-entered attribute. Content that is not entered by the user, without validation.
2, the Operation field in the database (even if it is generated by the system, such as creation time, update time and other fields-in the Boylee provided by the Yii_computer source code, the system generated these properties are not put in safe. See code below). data that is not provided by the form is added to safe as long as it is not validated in the rules method, otherwise it cannot be written to the database.
The news.php model of Yii_computer about the Rules method
/** * @return Array validation rules for model attributes. */public function Rules () { //note:you should only define rules for those attributes that //would receive user in Puts. 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 this should not be searched. Array (' ID, news_title, news_content, Author_name, type_id, status_id ', ' safe ', ' on ' = ' search '), );
Three ways to display dynamic content in a view
1, directly in the view file in the PHP code implementation. For example, display the current time in the view: copy code code as follows: <?php echo date ("y-m-d h:i:s");? >
2, implement the display content in the controller, pass the second parameter of render to the view
The Controller method contains:
$theTime =date ("y-m-d h:i:s"); $this->render (' HelloWorld ', Array (' time ' = $theTime));
View File:
Copy the Code code as follows: <?php echo $time;? >
The data for the second parameter of the call to the render () method is an array (array type), and the render () method extracts the values from the array provided to the view script, and the key (key value) in the array will be the variable name provided to the view script. In this example, the array key (the key value) is Time,value (value) is $thetime the variable name that is extracted is used by the view script. This is a way to pass data from the controller to the view.
3. The view and controller are very close brothers, so the $this in the view file refers to the controller that renders the view. Modify the previous example to define a public property of a class in the controller, not a local variable, which is the current date and time of the value. The properties of this class are then accessed through $this in the view.
View Naming conventions
The view file is named the same as ActionId. But keep in mind that this is only a recommended naming convention. In fact, the view file name does not have to be the same as ActionId, just pass the name of the file as the first parameter to render ().
DB correlation
$PRERFP = Prerfp::model ()->findall ( Array ( ' limit ' = ' 5 ', ' order ' = ' releasetime desc ' ));
$model = Finishrfp::model ()->findall ( Array ( ' select ' = ' companyname,title,releasetime ', ' Order ' = ' = ' releasetime desc ', ' limit ' = +) ; foreach ($model as $val) { $NOTICEARR [] = "in". $val Title. " Bidding, ". $val->companyname." Winning bidder. ";}
$model = Cgnotice::model ()->findall ( Array ( ' select ' = ' status,content,updatetime ', ' condition ' = ' status =: Status ', ' params ' = = Array (': Status ' =>0), ' order ' = ' updatetime desc ', ' ) , 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 line of postid=10 $post=post::model ()->find (' postid=:p ostid ', Array (':p ostid ' =>10));
You can also use $condition to specify more complex query conditions. Without using strings, we can make $condition an instance of Cdbcriteria, which allows us to specify conditions that are not limited to where. For example:
$criteria =new Cdbcriteria; $criteria->select= ' title '; Select only the ' title ' column $criteria->condition= ' postid=:p ostid '; $criteria->params=array (':p ostid ' =>10); $post =post: : Model ()->find ($criteria); $params don't need it.
Note that when Cdbcriteria is used as a query condition, the $params parameter is no longer needed because it can be specified in Cdbcriteria, as in the above.
One way to replace Cdbcriteria is to pass an array to the Find method. The key and value of the array correspond to the property name and value of the standard (criterion), and the above example can be rewritten as follows:
$post =post::model ()->find (Array (' SELECT ' = ' title ', ' condition ' = ' postid=:p ostid ', ' params ' =>array (': PostID ' =>10),));
Other
1. Links
Copy the Code code as follows:<?php Echo Chtml::link (Controller::utf8_substr ($val->title,0,26), Array (' prerfp/ Details ', ' id ' = = $val->rfpid), array (' target ' = ' _blank '));? >
Find API documentation specifically: cHTML's link () method
Copy the Code code as follows:title;? > "href=" <?php Echo $this->createurl (' prerfp/details ', array (' id ' = = $val->rfpid));? > "><?php echo controller::utf8_substr ($val->title,0,26);?>
Please find the API documentation: Ccontroller's CreateURL () method
Above two connection effect equivalent
Component contains
An example:
At the bottom of the view is the following code:
Copy the Code code as follows: <?php $this->widget (' Notice ');?>
Opens the notice.php file under Protected/components, with the following contents:
<?phpyii::import (' Zii.widgets.CPortlet '); class Banner extends cportlet{ protected function rendercontent () { $this->render (' banner ');} }
The rendered view is banner in the Protected/components/views directory.
Specific view API, keyword:cportlet
Gets 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;
About adding CKEditor extensions when you publish 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: D:\wwwroot\blog directory. Then the value above is d:\wwwroot\blog\protected. Note that the path does not have a backslash at the end .
Echo Yii::app ()->baseurl;
If the project directory is in the: D:\wwwroot\blog directory. Then the value above is/blog. Note that the path does not have a backslash at the end .
(D:\wwwroot is the site root), Note the above two differences. One is BasePath, one is BaseURL.
Others (not necessarily correct)
In a view corresponding to controller A, the method in the B model is called, using the method name () in the B::model ()->b model;
Some APIs that need to be mastered earlier
CHtml
It is hoped that this article is helpful to the PHP program design based on YII framework.