In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail the common mistakes in the use of PHP's Yii framework. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
1. The introduction of Js and Css files in Yii.
Let's start with the simplest question. It's not a problem, it's just grammar. Suppose our js files are placed in the js folder on the same level as protected, and the css files are placed in the css folder on the same level as protected. Well, that's the specification. Then we can write in the corresponding view interface as follows. The parameters of css and js functions are different. (it was adjusted for an hour because of this.)
The second parameter to register the js file is the location of the js. There are three options: CClientScript::POS_HEAD in the Head section, CClientScript::POS_BEGIN at the beginning of the Body, CClientScript::POS_END at the end of the Body, no need to fill it out without special requirements. The second parameter for registering the Css file is for media, interested students to click here, which is still the default for now.
For a js like Jquery, using registerCoreScript will not cause inexplicable mistakes.
/ / register js file Yii::app ()-> clientScript- > registerScriptFile (Yii::app ()-> baseUrl.'/js/project1.js',CClientScript::POS_HEAD); / / register css file Yii::app ()-> clientScript- > registerCssFile (Yii::app ()-> baseUrl.'/css/project1.css'); / / register Jquery file Yii::app ()-> clientScript- > registerCoreScript ('jquery')
2. Yii isNewRecord repair
The isNewRecord attribute of Yii's Model is very useful and can be discussed on a case-by-case basis. However, if we open the transaction mechanism or other circumstances, causing the data to be inserted and then rolled back, there is no such record in the database, but isNewRecord is flase, which means that it is no longer a new record. The solution is to use the primary key to access the database to determine whether it is a new record, and we need to click on the following before we use this property. The following Model is Post and the primary key is id:
If (! $model- > isNewRecord) {$db_exist = Post::model ()-> findByPk ($model- > id); if ($db_exist = = NULL) $model- > isNewRecord = true;}
3.Yii generates hidden input fields
Although it's easy to write an input field by yourself (it's just display:none), sometimes you need to follow the Yii form code format, anyway, just one sentence.
4. Yii generates a drop-down menu
Many times we need a drop-down menu in form, when Chtml's listdata is easy to use. If there are only a few possible fields in our database, such as 0 and 1, you can write as follows:
Echo $form- > dropDownList ($model,'is_marry',array ('0percent = >' No', '1percent = >' Yes'))
At this point, what you see is the drop-down menu of "No". When you select "Yes" to submit, this field is filled in as 1, and "No" is 0. Of course, it's often more than that. We can add a function to Model to generate an array of drop-down menus, and then call it in view. The data of this function can be written by itself or found in the database. Listdata is used below, specifically, with id in model as the key and name as the value.
/ * write in model * / public function getUserOptions () {$models = User::model ()-> findAll (); $models = User::model ()-> findAllByAttributes (array ('is_regeister'= >' 1'); return CHtml::listdata ($models, 'id',' name');} / * in the interface of view * / echo $form- > dropDownList ($model,'user_id',User::model ()-> getUserOptions ())
5.Yii enables transaction mechanism
When you save several records to the database at the same time, you may need to turn on the transaction mechanism. It is easy for Yii to start the transaction mechanism, as long as three sentences are enough.
/ * enable transaction mechanism * / $transaction = Yii::app ()-> db- > beginTransaction (); if try is successful, commit * / $transaction- > commit ();} catch (Exception $e) {$transaction- > rollBack ();}
A more complete one like this:
If ($_ POST ['ModelA']) {/ * enable transaction mechanism * / $transaction = Yii::app ()-> db- > beginTransaction (); try {/ * omit a bunch of logic here * / $modelA- > save (); $modelB- > save (); / * commit * / $transaction- > commit () if successful; $this- > redirect (' view','id'= > $model- > id)) } catch (Exception $e) {$transaction- > rollBack ();}}
But I usually like the following, what benefits please experience by yourself.
If ($_ POST ['ModelA']) {/ * enable transaction mechanism * / $transaction = Yii::app ()-> db- > beginTransaction (); try {$validated = true; / * omit a pile of logic here * / $valid = $modelA- > save (); $validated = $valid & $validated; / * A pile of logic continues to be omitted here * / $valid = $modelB- > save (); $validated = $valid & $validated / * commit * / if ($validated) {$transaction- > commit (); $this- > redirect ('view','id'= > $model- > id));} else {/ * rollback if not successful * / $transaction- > rollBack ();} catch (Exception $e) {$transaction- > rollBack ();}}
6. There was an error querying the same field in the associated table.
Sometimes we build two tables, but the two tables have the same field. When using CDbCriteria for with associated query search, if there is no additional setting, there will be a query error, which roughly means that the Mysql statement is ambiguous. At this point, we can just set an alias in the main table, and then be careful to add the name when querying the relevant fields.
For example, two Model, Post and User, each have an id, and we can write something like this:
$criteria=new CDbCriteria; $criteria- > alias = "post"; $criteria- > with = array ('user'); $criteria- > compare (' post.id',$Post- > id,true); $model = Post::model ()-> find ($criteria)
7. File upload
Speaking of this is not Yii, basically are native HTML and PHP, lazy score, just put it here.
Below is HTML,action changed to your own url, and id and name are also defined by you.
File upload
This is the code that the server receives and saves the file, and the file is finally saved to the file folder of the attached folder:
If (isset ($_ FILES ['file1'])) {$xlsfile = $_ FILES [' file1']; $tmp_name = $xlsfile ['tmp_name']; / * get file name * / $file_name = basename ($xlsfile_name); if ($xlsfile [' error'] > 0) {echo "file upload error! please try again." ; exit;} else {if (file_exists ("attached/tmp/". $file_name)) echo "file already exists! do not save this time!" ; else {if (! is_dir ("attached/tmp/")) {/ * create a new folder. The default permission 777MagneTrue means that you can recursively create * / if (! mkdir ("attached/tmp/", 0777djue true) {echo "could not find the attached/tmp folder and failed to create it!" ; exit;}} / * this function is only used for the movement of uploaded files * / move_uploaded_file ($tmp_name, "attached/tmp/". $file_name);}
The following is to move the existing files from the old_file path to the current date folder in attached/file. Rename is used for mobile here
/ * create a folder * / $date = date ('YmurmMaidongjinghe time ()); $date = str_replace (' -', ", $date); $dir =" attached/file/ ". $date.'/'; if (! is_dir ($dir)) {if (! mkdir ($dir,0777,true)) {exit ('unable to create folder!');}} / * move files * / $file_name = basename ($old_file) $finish = rename ($old_file,$dir.$file_name); if (! $finish) {exit ('cannot move file!');}
8.YIi scenarios and Security Fields
View the current Model scene:
Var_dump ($model- > scenario)
View the security fields of the scene. The security field means that the data will not be filtered by Yii when submitted by the user. On one occasion, I found that some of the things submitted on the web page were not there, and it took me a long time to know that part of the scene had been filtered.
$arr = $model- > getSafeAttributeNames ($model- > scenario); var_dump ($arr)
Force assignment to avoid filtering fields by rule rules. You can use setAttributes to force the security filtering of Yii, as long as the second parameter is assigned to false. But this only works for the fields that the Model had when it was generated. If you want to not filter all the fields that you define, it is better to define the scenario and specify the security field in the rule.
If (isset ($_ GET ['Po'])) $model- > setAttributes ($_ GET [' Post'], false)
Check the validity of date format
Sometimes we need to check whether the date filled in by the user is legal, we can use the following function.
Function checkDatetime ($dateStr, $format = "Y-m-d H:i:s") {$time = strtotime ($dateStr); $checkDate = date ($format, $time); return $checkDate = = $dateStr;}
Yii rendering multiple model
I believe beginners are confused. The forms in _ form render a model and then submit it to controller to save the data. What if you want to render multiple model?
Next, let's assume that there are two model classes, called Person and Addr, and what we want to do is render a few more model of Addr in the _ form of a Person, meaning that a person can have several addresses. The basic idea is actually very simple, that is, you define the model to be rendered in controller, then pass it to the view interface, and finally still receive the data from Post in controller. It's mainly a question of writing. I'm sure everyone can understand it below. leave a message for the children's shoes in question.
/ / in controller, $model=new Person; / * $addrs stores an array of Addr model, and you can count on it * / $addrs = array (); if (isset ($_ POST ['Person'])) {$model- > attributes = $_ POST [' Person']; / * A bunch of logic * / foreach ($_ POST ['Addr'] as $one_addr) {$addr = new Addr (); $addr- > attributes = $one_addr) is omitted here. / * omit another pile of logic here * /}} $this- > render ('create',array (' model'= > $model, 'addrs' = > $addrs,)); / / in view / * you can loop out your multiple model * / $num = count ($addrs); for ($I = 0
< $num;++$i) { echo $form->LabelEx ($addrs [$I], "[{$I}] postcode"); echo $form- > textField ($addrs [$I], "[{$I}] postcode", array ('size'= > 10 echo form- > labelEx ($addrs [0], "[0] postcode"); echo $form- > textField ($addrs [0], "[0] postcode", array (' size'= > 10 postcode = > 10)) This is the end of this article on "what are the common mistakes in the use of PHP's Yii framework?" I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.