鍍金池/ 教程/ PHP/ Coding Practices
入門指南
緩存
服務(wù)器和部署
測(cè)試
資源
數(shù)據(jù)庫(kù)
安全
Coding Practices
代碼風(fēng)格指南
語(yǔ)言亮點(diǎn)
依賴管理

Coding Practices

基礎(chǔ)知識(shí)

PHP是一個(gè)偉大的語(yǔ)言,可以讓各個(gè)層次的程序員都能夠快速高效地完成編碼任務(wù)。雖然如此,我們還是經(jīng)常會(huì)因?yàn)榕R時(shí)救急或者 壞習(xí)慣而忽視了PHP的基礎(chǔ)。為了解決這個(gè)問題,這部分專門給開發(fā)者回顧一下PHP的基礎(chǔ)編碼實(shí)踐。

日期和時(shí)間

PHP使用DateTime類完成讀取、設(shè)置、比較和計(jì)算日期與時(shí)間。雖然PHP中有很多日期和時(shí)間處理相關(guān)的函數(shù),但是DateTime類提供了 完善的面向?qū)ο蠼涌谕瓿筛黜?xiàng)常見操作,而且還能處理時(shí)區(qū),這里不作深入介紹。

要使用DateTime,可以用工廠方法createFromFormat()把原始的日期時(shí)間字符串轉(zhuǎn)換為DateTime對(duì)象,或直接用new DateTime 獲得當(dāng)前日期和時(shí)間的DateTime對(duì)象。用format()方法可以把DateTime對(duì)象轉(zhuǎn)換成字符串輸出。

<?php
$raw = '22. 11. 1968';
$start = \DateTime::createFromFormat('d. m. Y', $raw);

echo "Start date: " . $start->format('m/d/Y') . "\n";

DateTime計(jì)算時(shí)間時(shí)通常需要DateInterval類,如add()sub()方法,都是將DateInterval作為參數(shù)。盡量避免直接用 時(shí)間戳表示時(shí)間,夏令時(shí)和時(shí)區(qū)會(huì)讓時(shí)間戳產(chǎn)生歧義,使用間隔日期更為妥當(dāng)。計(jì)算兩個(gè)日期的差值使用diff()方法,返回 DateInterval對(duì)象,輸出顯示也很方便。

    <?php
// create a copy of $start and add one month and 6 days
$end = clone $start;
$end->add(new \DateInterval('P1M6D'));

$diff = $end->diff($start);
echo "Difference: " . $diff->format('%m month, %d days (total: %a days)') . "\n";
// Difference: 1 month, 6 days (total: 37 days)

DateTime對(duì)象之間可以直接比較:

<?php
if($start < $end) {
    echo "Start is before end!\n";
}

最后一個(gè)例子是DatePeriod類的用法,它用于循環(huán)事項(xiàng)(recurring events)的迭代。它的構(gòu)造函數(shù)參數(shù)為:start和end,均為 DateTime對(duì)象,以及返回事項(xiàng)的間隔周期。

<?php
// output all thursdays between $start and $end
$periodInterval = \DateInterval::createFromDateString('first thursday');
$periodIterator = new \DatePeriod($start, $periodInterval, $end, \DatePeriod::EXCLUDE_START_DATE);
foreach($periodIterator as $date)
{
    // output each date in the period
    echo $date->format('m/d/Y') . " ";
}

了解更多DateTime 學(xué)習(xí)更多日期格式化知識(shí) (accepted date format string options)

設(shè)計(jì)模式

在代碼和項(xiàng)目中使用常見模式是有好處的,可以讓代碼更易于管理,同時(shí)也便于其他開發(fā)者理解你的項(xiàng)目。

如果你的項(xiàng)目使用了框架,那么在代碼和項(xiàng)目結(jié)構(gòu)上,都會(huì)遵循框架的約束,自然也就繼承了框架中的各種模式, 這時(shí)你所需要考慮的是讓上層代碼也能夠遵循最合適的模式。反之,如果沒有使用框架,那么就需要你自己選擇 適用于當(dāng)前項(xiàng)目類型和規(guī)模的最佳模式了。

了解更多設(shè)計(jì)模式