[英]PHP performance question
想知道哪种会更好。 该站点将由已登录和未登录的用户查看。 对于已登录的用户,该站点几乎相同,只是他们拥有更多特权。 所以我想知道什么会更有效。
//选项一
if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}
//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.
我想知道使用选项一是否会更好,因为该功能将首先被检查一次,并且如果用户登录,则无需再次检查,如果未登录则将加载第一个块登录后,它将忽略第一个块并加载第二个块。
都不行 最好的选择是一次检查isLoggedIn,保存结果,然后在源内进行ifs交换。
第二个选项的性能负担可以忽略不计,但是它是更好的选择,因为它产生较少的代码重复。
另外,如果将isLoggedIn()的结果缓存在静态var中,则不必在每次调用该方法时都执行所有检查。 您可以检查您的静态变量并提早退出。
function isLoggedIn() {
static $is_logged_in = null;
if(!is_null($is_logged_in)) {
return $is_logged_in;
}
//... user is known not to have valid credentials
$is_logged_in = false;
// ... User has been validated
$is_logged_in = true;
//...
}
都。
您不想每次都检查isLoggedIn()
(尤其是如果要访问数据库时),因为这会很慢。 但是您也不想拥有2个版本的HTML,因为它们无法维护。
在顶部检查一次并设置一个变量(或使用会话变量进行检查)。 然后在HTML中使用针对变量的if语句确定要显示的内容。 例如:
PHP:
$logged_in = false;
if(isLoggedIn() ) {
$logged_in = true;
}
HTML:
<?php if($logged_in) { ?>
<div>
Super-secret needs a login stuff
</div>
<?php } else { ?>
<div>
Sorry! You have to login to see this cool stuff
</div>
<?php } ?>
我会说,如果可以的话,请为未登录的用户保留一个缓存的版本,并在他们登录时生成所有内容。
为了分离问题,让客户端浏览器为登录的用户添加功能可能是可行的。 这意味着您发送了一个静态版本的网站,而Javascript会在客户端检查登录cookie的存在。 如果存在,则会显示一些其他GUI元素或允许的链接。
明显的陷阱是禁用JS的浏览器看不到任何东西。 除非您使用CSS .optional-func装饰元素并禁用/启用:
if (!document.cookies.match(/login/)) { $(".user-funcs").hide(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.