[PHP]Yii2框架的坑,phpyii2框架_PHP教程
Jul 13, 2016 am 09:44 AM[PHP]Yii2框架的坑,phpyii2框架
Yii2框架的幾個(gè)隱蔽的坑
摘要:Yii2是一款優(yōu)秀的通用Web后端框架,結(jié)構(gòu)簡(jiǎn)單優(yōu)雅、實(shí)用功能豐富、擴(kuò)展性強(qiáng)、性能搞是他最突出的優(yōu)點(diǎn)。它優(yōu)秀的地方你在使用過(guò)程中總能輕易的發(fā)現(xiàn),無(wú)須贅述。而這些隱蔽的小瑕疵,顯得更有必要告訴大家。
- 博客: http://www.cnblogs.com/jhzhu
- 郵箱: jhzhuustc@gmail.com
- 作者: 知明所以
- 時(shí)間: 2015-08-17
目錄
- Yii2框架的幾個(gè)隱蔽的坑
- 目錄
- 說(shuō)點(diǎn)閑話
- ActiveRecord被莫名寫(xiě)入?
- 準(zhǔn)備知識(shí)
- 代碼現(xiàn)場(chǎng)
- 總結(jié)問(wèn)題
- 解決方法
- 你的Transaction生效了嗎?
- 代碼現(xiàn)場(chǎng)
- 問(wèn)題總結(jié)
- 解決方法
- 'Y-m-d'不被識(shí)別?
- 代碼現(xiàn)場(chǎng)
- 問(wèn)題總結(jié)
說(shuō)點(diǎn)閑話
距離上次寫(xiě)博客,已經(jīng)有三個(gè)月了。在動(dòng)手寫(xiě)之前,總是帶著深深的罪惡感。被它折磨許久,終于,還是,動(dòng)手了。
值得慶祝的一件事:最近開(kāi)始,每天早上8:30起來(lái)健身了。有兩個(gè)視頻很好用,只需8分鐘,照著做一遍保證你(生)爽(不)到(如)爆(死)。(8分鐘腹肌鍛煉第2級(jí)-下載,8分鐘胸肌鍛煉第2級(jí)-下載)
值得反思的一件事:最近看了《叔本華美學(xué)隨筆》,改變了我一直以來(lái)對(duì)閱讀的看法。我曾經(jīng)以為閱讀是進(jìn)步的源動(dòng)力,卻被這本書(shū)深深的打臉了。來(lái),先給大家分享一段:
<p>我們只管所見(jiàn)的外在環(huán)境并不像閱讀物那樣,把某已確定的見(jiàn)解強(qiáng)加給我們的頭腦,而只是為我們提供了素材和機(jī)會(huì)。去思考與我們的頭腦能力相稱、與當(dāng)下的情緒相符的事情。所以,太多的閱讀會(huì)是我們的精神失去彈性,就像把一重物持續(xù)壓在一條彈簧上面就會(huì)是彈簧失去彈性一樣;而讓自己沒(méi)有自己思想的最穩(wěn)妥的辦法就是在空閑的每一分鐘馬上隨手拿起一本書(shū)。</p>
思考才是進(jìn)步的源動(dòng)力!
好了,扯淡完畢,步入正題。
ActiveRecord被莫名寫(xiě)入?
準(zhǔn)備知識(shí)
代碼現(xiàn)場(chǎng)
<span class="x">/**</span> <span class="x"> * @property integer $id</span> <span class="x"> * @property string $name</span> <span class="x"> * @property string $detail</span> <span class="x"> * @property double $price</span> <span class="x"> * @property integer $area</span> <span class="x"> **/</span> <span class="x">class OcRoom extends ActivieRecord</span> <span class="x">{</span> <span class="x"> ...</span> <span class="x">}</span> <span class="x">$room = OcRoom::find() //先取出一個(gè)對(duì)象。</span> <span class="x"> ->select(['id']) //只取出'id'列</span> <span class="x"> ->where(['id'=>20])</span> <span class="x"> ->one();</span> <span class="x">$room->save(); //保存,會(huì)發(fā)現(xiàn)此行的其它字段都被寫(xiě)成默認(rèn)值了。</span>
總結(jié)問(wèn)題
這個(gè)例子的問(wèn)題在于:
解決方法
然而,我們有什么解決辦法呢?提供幾種思路:
你的Transaction生效了嗎?
代碼現(xiàn)場(chǎng)
<span class="x">/**</span> <span class="x"> * @property integer $id</span> <span class="x"> * @property string $name</span> <span class="x"> **/</span> <span class="x">class OcRoom extends ActiveRecord</span> <span class="x">{</span> <span class="x"> public function rules()</span> <span class="x"> {</span> <span class="x"> return [['name','string','min'=>2,'max'=>10]];</span> <span class="x"> }</span> <span class="x"> ...</span> <span class="x">}</span> <span class="x">class OcHouse extends ActiveRecord</span> <span class="x">{</span> <span class="x"> public function rules()</span> <span class="x"> {</span> <span class="x"> return [['name','string','max'=>10]];</span> <span class="x"> }</span> <span class="x"> ...</span> <span class="x">}</span> <span class="x">$a = new OcRoom();</span> <span class="x">$a->name = ''; //name為空字符串,不滿足rules()條件。</span> <span class="x">$b = new OcHouse();</span> <span class="x">$b->name = '我的房間'; //name合法,可以保存。</span> <span class="x">$transaction = Yii::$app->db->beginTransaction();</span> <span class="x">try{</span> <span class="x"> $a->save(); //name字段不合法,無(wú)法驗(yàn)證通過(guò),在validate()階段已經(jīng)返回false,不會(huì)進(jìn)行數(shù)據(jù)庫(kù)存儲(chǔ)的步驟,所以也不會(huì)拋出異常。</span> <span class="x"> $b->save(); //name字段合法,可以正常保存。</span> <span class="x"> $transaction->commit(); //提交后,發(fā)現(xiàn)$a保存失敗,而$b保存成功。</span> <span class="x">}</span> <span class="x">catch (Exception $e) </span> <span class="x">{</span> <span class="x"> Yii::error($e->getTraceAsString(),__METHOD__);</span> <span class="x"> $transaction->rollBack();</span> <span class="x">}</span>
問(wèn)題總結(jié)
這段代碼的問(wèn)題在于:
解決方法
在$transation
塊內(nèi),所有的save()
都要判斷下返回值,如果為false
,則直接拋出異常。
'Y-m-d'不被識(shí)別?
代碼現(xiàn)場(chǎng)
<span class="x">OcRenterBill extends ActiveRecord</span> <span class="x">{</span> <span class="x"> public function rules()</span> <span class="x"> {</span> <span class="x"> return [</span> <span class="x"> ['start_time','date','format'=>'Y-m-d'],</span> <span class="x"> ];</span> <span class="x"> }</span> <span class="x">}</span> <span class="x">$a = new OcRenterBill();</span> <span class="x">$a = '2015-09-12';</span> <span class="x">$a->save(); //會(huì)報(bào)錯(cuò),說(shuō)格式不對(duì)。</span>
問(wèn)題總結(jié)
如果一開(kāi)始,Yii框架就報(bào)錯(cuò),這個(gè)還不算坑。坑的是我在Mac上開(kāi)發(fā)時(shí),這個(gè)可以完全正常的工作,而發(fā)布到線上環(huán)境(Ubuntu)后,就彈出“屬性start_time格式無(wú)效”的錯(cuò)誤。而參考官方文檔,發(fā)現(xiàn)這種格式是允許的官方文檔。
啊啊啊。各種試錯(cuò),最后發(fā)現(xiàn)如果改成php:Y-m-d
,世界就清凈了。所以,如果你遇到這種問(wèn)題,感激我吧。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
