2016-11-17 76 views
1

我很尷尬。PHP如果條件

我有三個函數來檢查用戶當前登錄是什麼:

public function isAuthor(User $user) 
{ 
    return $user->getId() === $this->getDestination(); 
} 

public function isSupervisor(User $user) 
{ 
    return $user->getId() === $this->getFirstApprover(); 
} 

public function isSecondApprover(User $user) 
{ 
    return $user->getId() === $this->getSecondApprover(); 
} 

然後,我想裏面添加我的行動的條件來檢查,如果用戶是任何上述三人。如果他不是其中之一,應該拒絕訪問。用戶有時可能不止一個,但大多隻有三個中的一個。

我是這樣的第一想法,但顯然它不能正常工作

if (!$object->isAuthor($this->getUser()) || !$object->isSupervisor($this->getUser()) || !$object->isSecondApprover($this->getUser())) { 
    throw new AccessDeniedException(); 
} 

會有什麼檢查,如果用戶是他們中的一個最好的辦法?我應該創建一個全新的功能嗎?

我應該使用這樣的事:

if (!$object->isAuthor($this->getUser())) { 
    throw new AccessDeniedException(); 
} elseif (!$object->isSupervisor($this->getUser())) { 
    throw new AccessDeniedException(); 
} 

我可以請有從別人的一些想法和投入?因爲我現在很困惑。 還在這裏一個新手

+4

在第一條件條件試驗中使用'&&而不是'||' – jitendrapurohit

+1

*「但顯然它不能工作」* - 爲什麼不呢?你只是混淆了你的布爾邏輯。你想'不是X並且不是Y AND不是Z',換句話說*「不是這些」*。目前,你正在表達*「如果這些中的任何一個是假的」* ... – deceze

回答

1

您的邏輯將工作,這是隻是一個「反向」布爾邏輯,很複雜編輯按照。它有一個錯誤,使用& &而不是||。

一種替代

if (! ( $object->isAuthor($this->getUser()) || 
     $object->isSupervisor($this->getUser()) || 
     $object->isSecondApprover($this->getUser())) 
{ 
    throw new AccessDeniedException(); 
} 

另一種選擇,你可以在 「對象」 類寫一個函數:

public function hasAccessLevelX(User $user) 
{ 
    return in_array($user->getId(), [ 
      $this->getDestination(), 
      $this->getFirstApprover(), 
      $this->getSecondApprover() 
    ]); 
} 

if (!$object->hasAccessLevelX($this->getUser())) { 
    throw new AccessDeniedException(); 
} 

我會用後者。

0

使用下面的代碼:

常用功能

public function userLogin(User $user) 
{ 
    $userId = $user->getId(); 
    if($userId == $this->getDestination() || 
     $userId == $this->getFirstApprover() || 
     $userId == $this->getSecondApprover()) 
    { 
     return TRUE;  
    } 
    return FALSE; 
} 

使用/通用功能的呼叫

if ($object->userLogin($this->getUser()) == FALSE) { 
    throw new AccessDeniedException(); 
} 
+0

請投票的人說出原因嗎?我認爲這看起來不錯。 –

+0

謝謝......我也擔心爲什麼下來選民沒有寫出適當的評論和理由。再次感謝。接受如果對你有用。 @JackCoolen – RJParikh

+0

這是錯誤的命名和返回值。 「userLogin是0」是什麼意思*?沒什麼。這是一個暗含意義的幻數。這應該是'userIsLoggedIn'並返回'boolean',這是自我解釋。 – deceze