锁定老帖子 主题:PHP 编程的 5 个良好习惯
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-06-25
像其他语言一样,开发人员可以用 PHP 编写出各种质量级别的代码。学习良好的编程习惯能够提高代码质量和效率。
<?php function getNBDay($d) { switch($d) { case 5: case 6: case 7: return 1; default: return ($d + 1); } } $day = 5; $nextDay = getNBDay($day); echo ("Next day is: " . $nextDay . "\n"); ?> 良好习惯:说明性强并且简洁的名称
<?php define ('MONDAY', 1); define ('TUESDAY', 2); define ('WEDNESDAY', 3); define ('THURSDAY', 4); define ('FRIDAY', 5); define ('SATURDAY', 6); define ('SUNDAY', 7); /* * * @param $dayOfWeek * @return int Day of week, with 1 being Monday and so on. */ function findNextBusinessDay($dayOfWeek) { $nextBusinessDay = $dayOfWeek; switch($dayOfWeek) { case FRIDAY: case SATURDAY: case SUNDAY: $nextBusinessDay = MONDAY; break; default: $nextBusinessDay += 1; break; } return $nextBusinessDay; } $day = FRIDAY; $nextBusDay = findNextBusinessDay($day); echo ("Next day is:" . $nextBusDay . "\n"); ?> 我们鼓励您将大的条件拆分为一个方法,然后用能够描述该条件的名字命名方法。这个技巧能够提高代码的可读性,并且能够将条件具体化,使之能够被提取甚至重用。如果条件发生变化,更新方法也很容易。因为方法拥有一个有意义的名字,所以它能反映代码的用途,让代码更容易阅读。
<?php function writeRssFeed($user) { // Get the DB connection information // look up the user's preferences... $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') OR die(mysql_error()); // Query $perfsQuery = sprintf("SELECT max_stories FROM user_perfs WHERE user= '%s'", mysql_real_escape_string($user)); $result = mysql_query($query, $link); $max_stories = 25; // default it to 25; if ($row = mysql_fetch_assoc($result)) { $max_stories = $row['max_stories']; } // go get my data $perfsQuery = sprintf("SELECT * FROM stories WHERE post_date = '%s'", mysql_real_escape_string()); $result = mysql_query($query, $link); $feed = "<rss version=\"2.0\">" . "<channel>" . "<title>My Great Feed</title>" . "<link>http://www.example.com/feed.xml</link>" . "<description>The best feed in the world</description>" . "<language>en-us</language>" . "<pubDate>Tue, 20 Oct 2008 10:00:00 GMT</pubDate>" . "<lastBuildDate>Tue, 20 Oct 2008 10:00:00 GMT</lastBuildDate>" . "<docs>http://www.example.com/rss</docs>" . "<generator>MyFeed Generator</generator>" . "<managingEditor>editor@example.com</managingEditor>" . "<webMaster>webmaster@example.com</webMaster>" . "<ttl>5</ttl>"; // build the feed... while ($row = mysql_fetch_assoc($result)) { $title = $row['title']; $link = $row['link']; $description = $row['description']; $date = $row['date']; $guid = $row['guid']; $feed .= "<item>"; $feed .= "<title>" . $title . "</title>"; $feed .= "<link>" . $link . "</link>"; $feed .= "<description> " . $description . "</description>"; $feed .= "<pubDate>" . $date . "</pubDate>"; $feed .= "<guid>" . $guid . "</guid>"; $feed .= "</item>"; } $feed .= "</rss"; // write the feed out to the server... echo($feed); } ?> 如果多编写几个这样的方法,维护就成了真正的难题了。
<?php function createRssHeader() { return "<rss version=\"2.0\">" . "<channel>" . "<title>My Great Feed</title>" . "<link>http://www.example.com/feed.xml</link>" . "<description>The best feed in the world</description>" . "<language>en-us</language>" . "<pubDate>Tue, 20 Oct 2008 10:00:00 GMT</pubDate>" . "<lastBuildDate>Tue, 20 Oct 2008 10:00:00 GMT</lastBuildDate>" . "<docs>http://www.example.com/rss</docs>" . "<generator>MyFeed Generator</generator>" . "<managingEditor>editor@example.com</managingEditor>" . "<webMaster>webmaster@example.com</webMaster>" . "<ttl>5</ttl>"; } function createRssFooter() { return "</channel></rss>"; } function createRssItem($title, $link, $desc, $date, $guid) { $item .= "<item>"; $item .= "<title>" . $title . "</title>"; $item .= "<link>" . $link . "</link>"; $item .= "<description> " . $description . "</description>"; $item .= "<pubDate>" . $date . "</pubDate>"; $item .= "<guid>" . $guid . "</guid>"; $item .= "</item>"; return $item; } function getUserMaxStories($db_link, $default) { $perfsQuery = sprintf("SELECT max_stories FROM user_perfs WHERE user= '%s'", mysql_real_escape_string($user)); $result = mysql_query($perfsQuery, $db_link); $max_stories = $default; if ($row = mysql_fetch_assoc($result)) { $max_stories = $row['max_stories']; } return $max_stories; } function writeRssFeed($user) { // Get the DB connection information $settings = parse_ini_file("rss_server.ini"); // look up the user's preferences... $link = mysql_connect($settings['db_host'], $settings['user'], $settings['password']) OR die(mysql_error()); $max_stories = getUserMaxStories($link, 25); // go get my data $newsQuery = sprintf("SELECT * FROM stories WHERE post_date = '%s'", mysql_real_escape_string(time())); $result = mysql_query($newsQuery, $link); $feed = createRssHeader(); $i = 0; // build the feed... while ($row = mysql_fetch_assoc($result)) { if ($i < $max_stories) { $title = $row['title']; $link = $row['link']; $description = $row['description']; $date = $row['date']; $guid = $row['guid']; $feed .= createRssItem($title, $link, $description, $date, $guid); $i++; } else { break; } } mysql_close($link); $feed .= createRssFooter(); // write the feed out to the server... echo($feed); } ?>
将长方法拆分为短方法也是有限制的,过度拆分将适得其反。因此,不要滥用这个良好的习惯。将代码分成大量的片段就像没有拆分长代码一样,都会造成阅读困难。
<?php class ResultMessage { private $severity; private $message; public function __construct($sev, $msg) { $this->severity = $sev; $this->message = $msg; } public function getSeverity() { return $this->severity; } public function setSeverity($severity) { $this->severity = $severity; } public function getMessage() { return $this->message; } public function setMessage($msg) { $this->message = $msg; } } function cntMsgs($messages) { $n = 0; /* iterate through the messages... */ foreach($messages as $m) { if ($m->getSeverity() == 'Error') { $n++; // add one to the result; } } return $n; } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = cntMsgs($messages); echo("There are " . $errs . " errors in the result.\n"); ?> 良好习惯:带注释的函数和类
<?php /** * The ResultMessage class holds a message that can be returned * as a result of a process. The message has a severity and * message. * * @author nagood * */ class ResultMessage { private $severity; private $message; /** * Constructor for the ResultMessage that allows you to assign * severity and message. * @param $sev See {@link getSeverity()} * @param $msg * @return unknown_type */ public function __construct($sev, $msg) { $this->severity = $sev; $this->message = $msg; } /** * Returns the severity of the message. Should be one * "Information", "Warning", or "Error". * @return string Message severity */ public function getSeverity() { return $this->severity; } /** * Sets the severity of the message * @param $severity * @return void */ public function setSeverity($severity) { $this->severity = $severity; } public function getMessage() { return $this->message; } public function setMessage($msg) { $this->message = $msg; } } /* * Counts the messages with the given severity in the array * of messages. * * @param $messages An array of ResultMessage * @return int Count of messages with a severity of "Error" */ function countErrors($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Error") { $matchingCount++; } } return $matchingCount; } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = countErrors($messages); echo("There are " . $errs . " errors in the result.\n"); ?>
4. 处理错误
<?php // Get the actual name of the function convertDayOfWeekToName($day) { $dayNames = array( "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); return $dayNames[$day]; } echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n"); echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n"); echo("The name of the 'orange' day is: " . convertDayOfWeekToName('orange') . "\n"); ?>
良好习惯:处理异常
<?php /** * This is the exception thrown if the day of the week is invalid. * @author nagood * */ class InvalidDayOfWeekException extends Exception { } class InvalidDayFormatException extends Exception { } /** * Gets the name of the day given the day in the week. Will * return an error if the value supplied is out of range. * * @param $day * @return unknown_type */ function convertDayOfWeekToName($day) { if (! is_numeric($day)) { throw new InvalidDayFormatException('The value \'' . $day . '\' is an ' . 'invalid format for a day of week.'); } if (($day > 6) || ($day < 0)) { throw new InvalidDayOfWeekException('The day number \'' . $day . '\' is an ' . 'invalid day of the week. Expecting 0-6.'); } $dayNames = array( "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); return $dayNames[$day]; } echo("The name of the 0 day is: " . convertDayOfWeekToName(0) . "\n"); try { echo("The name of the 10 day is: " . convertDayOfWeekToName(10) . "\n"); } catch (InvalidDayOfWeekException $e) { echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n"); } try { echo("The name of the 'orange' day is: " . convertDayOfWeekToName('orange') . "\n"); } catch (InvalidDayFormatException $e) { echo ("Encountered error while trying to convert value: " . $e->getMessage() . "\n"); } ?>虽然检查参数是一种确认 — 如果您要求参数处于某种状态,这将对使用方法的人很有帮助 — 但是您应该检查它们并抛出有意义的异常:
<?php /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Error" * * @param $messages An array of ResultMessage * @return unknown_type */ function countErrors($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Error") { $matchingCount++; } } return $matchingCount; } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Warning" * * @param $messages An array of ResultMessage * @return unknown_type */ function countWarnings($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Warning") { $matchingCount++; } } return $matchingCount; } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Information" * * @param $messages An array of ResultMessage * @return unknown_type */ function countInformation($messages) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == "Information") { $matchingCount++; } } return $matchingCount; } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = countErrors($messages); echo("There are " . $errs . " errors in the result.\n"); ?>良好习惯:带参数的可重用函数
<?php /* * Counts the messages with the given severity in the array * of messages. * * @param $messages An array of ResultMessage * @return int Count of messages matching $withSeverity */ function countMessages($messages, $withSeverity) { $matchingCount = 0; foreach($messages as $m) { if ($m->getSeverity() == $withSeverity) { $matchingCount++; } } return $matchingCount; } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Error" * * @param $messages An array of ResultMessage * @return unknown_type */ function countErrors($messages) { return countMessages($messages, "Errors"); } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Warning" * * @param $messages An array of ResultMessage * @return unknown_type */ function countWarnings($messages) { return countMessages($messages, "Warning"); } /** * Counts the number of messages found in the array of * ResultMessage with the getSeverity() value of "Warning" * * @param $messages An array of ResultMessage * @return unknown_type */ function countInformation($messages) { return countMessages($messages, "Information"); } $messages = array(new ResultMessage("Error", "This is an error!"), new ResultMessage("Warning", "This is a warning!"), new ResultMessage("Error", "This is another error!")); $errs = countErrors($messages); echo("There are " . $errs . " errors in the result.\n"); ?>结束语
出处:http://club.topsage.com/forum.php?mod=viewthread&tid=349673&page=1#pid12376282
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
浏览 5931 次