Question

I'm a little confused with this OOP concept. I'm trying to set a value for a varable below;.

ie:

protected  $isAdmin; 

I want to use a setter and getter to set this values; and use a caseMethod to set the values for the setter.

It might be easier to show you below;

 protected  $isAdmin = null;  

    public function isAdminWorker()
    {
        //this will get the preset values for the user; i.e admin worker or visitor.
        $theRole = $this->zfcUserAuthentication()->getAuthService()->getIdentity()->getRole();

    switch($theRole)
    {               
            case 'admin':

              $this->setIsAdmin($theRole);

        break;

            case 'visitor':
               $this->setVisitor($theRole);
        break;
        }    
    }

public function setIsAdmin($isAdmin)
    {
         $this->isAdmin = $isAdmin;
    } 

    public function getIsAdmin()
    {

        return $this->isAdmin;
    } 

When I called the $this->getIsAdmin() it always returned a NULL value. So, the Case method is basically not setting the correct values.

I'm obviouly confused about setting values using the getter and setter method and would appriciate some advice on where I have gone wrong.

Was it helpful?

Solution

I'm obviouly confused about setting values using the getter and setter method and would appriciate some advice on where I have gone wrong

isFoo() or hasFoo() ("is" or "has" methods) are normally used to signify a boolean result.

I think if you are combining the is and get methods together it would lead to confusion.

Try to encapsulate the methods so they perform one task; a possible solution might be.

class MyClass {

  protected $identity;

  protected $role;

  public function getIdentity()
  {
    if (null == $this->identity) {
      $this->identity = $this->zfcUserAuthentication()->getAuthService()->getIdentity();
    }
    return $this->identity;
  }

  public function getRole()
  {
    if (null == $this->role) {
      $this->role = $this->getIdentity()->getRole();
    }
    return $this->role;
  }

  public function isAdmin()
  {
    return ('admin' === $this->getRole());
  }

  public function isVisitor()
  {
    return ('visitor' === $this->getRole());
  }

}  

This gives you a clearer API and no need to "set" any roles etc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top