2015-02-10 46 views
0

我爲我的Magento模塊的一部分編寫了一個模型,用於檢查用戶是否已登錄。它旨在防止未登錄的用戶訪問某些頁面。它有效,但我有興趣學習Magento最佳實踐並編寫更高效的代碼。在這個模型中,我需要檢查用戶是否登錄。這給了我兩個選擇。我可以在代碼中調用法師助手,也可以擴展Mage_Customer_Helper_Data類並詢問$this->isLoggedIn()。哪個效率最高?有沒有更好的辦法?我將粘貼下面的兩個版本。Magento - 調用輔助函數或擴展輔助類更有效嗎?

延長幫手

class Company_Module_Model_Protection extends Mage_Customer_Helper_Data 
{ 
    public function checkUser() 
    { 
     if (!$this->isLoggedIn()) 
     { 
      Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('customer/account/login/referer/'.base64_encode(Mage::helper('core/url')->getCurrentUrl()).'/')); 
     } 
     return true; 
    } 
} 

調用輔助

class Company_Module_Model_Protection 
{ 
    public function checkUser() 
    { 
     if (!Mage::helper('customer')->isLoggedIn()) 
     { 
      Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('customer/account/login/referer/'.base64_encode(Mage::helper('core/url')->getCurrentUrl()).'/')); 
     } 
     return true; 
    } 
} 

回答

1

兩者都是完全可以接受的,一個將有幫手實例另一個幫手,讓你可以有一點點在調用核心幫手方面獲得延期。

但是,看到並確定它的最好方法是對它進行基準測試,Magento探查器是實現該任務的最好的朋友。

現在說,如果你想有一個非常清晰的模塊,你現在必須改變你的模塊定義(在app/etc/modules/),清楚地表明你自己的模塊需要Mage_Customer才能正常工作。

所以/app/etc/modules/Company_Module.xml

<?xml version="1.0"?> 
<config> 
    <modules> 
     <Company_Module> 
      <active>true</active> 
      <codePool>local</codePool> 
      <depends> 
       <Mage_Customer/> 
      </depends> 
     </Company_Module> 
    </modules> 
</config> 

這樣一來,如果有人安裝模塊與Magento的上Mage_Customer被禁止,他會看到一個明確的警告,客戶模塊已被激活。你可以肯定的是你的extends,呼叫核心幫手或getUrl客戶模塊控制器應該永遠不會失敗。

+0

我喜歡它,非常感謝你的提示! – Markie 2015-02-10 11:06:36