簡體   English   中英

PHP性能問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM