开发者

PHP: If many objects use instance of the same object - what is an efficient way to pass it?

For example, my app is using instance of a User object,开发者_C百科 and different other objects have to access some attributes and methods. And these objects instantiate other objects, which in turn also have to access User. What's the best way to manage this? Pass User object as reference when I instantiate these new objects?

Here's example of how this is done now:

class App {
  private $user;
  private $controller;

  public function __construct() {
    $this->user = new User();
    $this->controller = new Controller();
    $this->controller->setUser(& $this->user);
  }  
}

Is this the right way to do it?

EDIT: Is there a way to make User instance a global var?


Just to make my suggestion in the comments to an answer

You can implement the singleton pattern

class User {
    protected static $instance = null;
    protected function __construct () { /* disable external instanciation */ }
    private function __clone () { /* disable clone */ }
    public static function getInstance () {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

Here is something to read :)

http://en.wikipedia.org/wiki/Singleton_pattern


Is there a way to make User instance a global var?

It sounds like a singleton would be helpful:

class User
{
  private static $instance;

  private function __construct() { } 

  public function instance()
  {
    return self::$instance ? self::$instance : (self::$instance = new self());
  }
}

$user = User::instance();

Basically anything that needs the user, can just call User::instance() instead of new User(). They will all be operating on the same instance of the object, so this is only applicable of the User object represents the same data throughout the duration of the script.

Update

With your comment "No, it's possible for one user to perform actions on other user," then this pattern is not applicable for every usage.

Sounds like you just need to pass the $user object along to anybody that needs it. (Of course, you could still use a singleton to represent the authenticated user.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜