Which pattern should I use for my unique instance of the User class?

前端 未结 6 880
醉梦人生
醉梦人生 2021-01-14 18:51

I have this User class

class User{
  private    $logged = false;
  private    $id;

  public function User() {
      //> Check if the user is logged in wi         


        
6条回答
  •  情书的邮戳
    2021-01-14 19:45

    Not sure why all the arguing up top. Seems like a perfectly reasonable question to me.

    The key here is to use static members of the User class. Static methods are your friends, regardless of what some may say:

    class User
    {
       private    $logged = false;
       private    $id;
    
       private static $_currentUser;
       public static function currentUser()
       {
         if (empty(self::$_currentUser))
         {
             @session_start();
             if (array_key_exists('current_user', $_SESSION))
             {
                 self::$_currentUser = $_SESSION['current_user'];
             }
             else
             {
               // force login in or whatever else.
               // if you log in, make sure to call User::_setCurrentUser(); 
                 return null; //or some special 'empty' user.
             }
         }
         return self::$_currentUser;
      }
      // you may consider making this public, but it is private because it is a bit
      // more secure that way.  
      private static function _setCurrentUser(User $user)
      {
         self::$_currentUser = $user;
         $_SESSION['current_user'] = $user;
      }
    
      public function User() {
       //> Check if the user is logged in with a cookie-database and set $logged=true;
      }  
    
      public function isLogged() {}
      public function editPerms() {}
    
      //> other methods    
    }
    
    // Usage
    $pUser = User::currentUser();
    

提交回复
热议问题