开发者

Is there a better way to write this php code?

开发者 https://www.devze.com 2023-01-16 08:20 出处:网络
return\' <li> <a href=\"nano.com/\' . $username . \'\"><img class=\"avatar\" src=\"images/\' . $picture . \'\" width=\"48\" height=\"48\" alt=\"avatar\" /></a>
return'
    <li>
    <a href="nano.com/' . $username . '"><img class="avatar" src="images/' . $picture . '" width="48" height="48" alt="avatar" /></a>
    <div class="tweetTxt">
    <strong><a href="nano.com/' . $username . '">' . $username . '</a></strong> '. autolink($tweet).'
    <div class="date">'.relativeTime($dt).'</div><div class="date">'. $reply_info . '</div> <a class ="reply"  开发者_运维百科href="home.php?replyto=@'. $username .'&status_id='. $id .'&reply_name=' .$username.'"> reply </a>

    </div>
    <div class="clear"></div>
    </li>';

I was wondering if there is a cleaner way to write this code, and taking in mind processing time, if that really means anything.

p.s. this code is part of a function, this is the return statement!


Yes. Use double quotes for the PHP string (and single quotes for the HTML attributes), then you can just use PHP variables in the string, like so:

"<a href='nano.com/$username'>";

Is processing time really an issue? I doubt it, but profile to be sure.


Edit: If anyone is unsure about using single quotes in HTML attributes, have a look at this question. It's pretty unanimously agreed that single quotes are fine. If anyone can give a decent counter-argument I'd be happy to hear it.


You could use HEREDOC syntax :

$auto = autolink($tweet);
$rel = relativeTime($dt);
return <<<ENDOFRETURN
    <li>
    <a href="nano.com/$username"><img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" /></a>
    <div class="tweetTxt">
    <strong><a href="nano.com/$username">$username</a></strong> $auto
    <div class="date">$rel</div><div class="date">$reply_info</div> <a class ="reply"  href="home.php?replyto=@$username&status_id=$id&reply_name=$username"> reply </a>
    </div>
    <div class="clear"></div>
    </li>
ENDOFRETURN;


Cleaner template and php code -> use MVC


Yes, there is one, and you don't need MVC (only a template):

<li>
 <a href="nano.com/<?=$username ?>">
  <img class="avatar" src="images/<?=$picture ?>" width="48" height="48" alt="avatar" />
 </a>
 <div class="tweetTxt">
  <strong><a href="nano.com/<?=$username ?>"><?=$username ?></a></strong>
  <? echo autolink($tweet) ?>
  <div class="date"><?=relativeTime($dt) ?></div>
  <div class="date"><?=$reply_info ?></div>
  <a class="reply" href="home.php?replyto=@<?=$username?>&status_id=<?=$id?>&reply_name=<?=$username?>">
  reply
  </a>
 </div>
 <div class="clear"></div>
</li>

Must read: http://wiki.yet-another-project.com/php/the_one_single_step_for_a_cleaner_code . It describes how you have to use the code above.


I would cut in several pieces and use sprintf() to tie it all together.


You can use a template engine i.e. smarty, twig, ...

0

精彩评论

暂无评论...
验证码 换一张
取 消