PHP OOP Good practice for accessing methods?

I have code that often looks like this:

private $user;

public function __construct()
{
    $this->user = User::getInstance(); //singleton
}

public function methodOne()
{
    return $this->user->foo();
}

public function methodTwo()
{
    return $this->user->foo2();
}

public function methodThree()
{
    return $this->user->foo3();
}

I believe that if I set the user property of the instance, I can reuse the shorter name in my methods (well, in this case, it is not much shorter). I also thought that doing it this way could save some resources (start to doubt it), but when I look at the code of other people, I rarely see how people do it. Usually they just call:

User::getInstance()->foo();
User::getInstance()->foo2();
User::getInstance()->foo3();

Is there any best practice for this? Maybe if this is not one class, can you do it like this? Or maybe you shouldn't do that? Hope to get clarification, thanks.

Edit: If there is any misunderstanding, I'm just wondering if I should create a property to store the vs this instance in the first example:

public function methodOne()
{
    return User::getInstance()->foo();
}

public function methodTwo()
{
    return User::getInstance()->foo2();
}

public function methodThree()
{
    return User::getInstance()->foo3();
}

, , , ...

+3
4

.

  • , User. , User .
  • . , : , , , ( ).
  • ( , , User:: method()). , . .

User , , , . , , , :

class Foo {
    public function __construct(User $user) {
        $this->user = $user;
    }
    public function doXsimplified() {
        $this->user->doXbutMoreComplex($arg1,$arg2, $arg20);
    }
}
+2

PHP - ,

User::foo();
User::bar();
+2

, . , . , , , .

$user = User::getInstance();
$user->foo();
$user->bar();

. Injection Dependency. sfServiceContainer, . : http://fabien.potencier.org/article/11/what-is-dependency-injection

UPDATE

, :

class UserWrapper
{
    private $user = null;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function foo()
    {
         return $this->user->foo();
    }

    ...
}

:

$user = new UserWrapper(User::getInstance());

Why? Therefore, I can pass a fake User object if I want to test the UserWrapper class. For instance:

class UserMock { ... } // A fake object that looks like a User
$userTest = new UserWrapper(new UserMock());
+2
source

I usually do this if you have already included a class in some type of bootstrap or configuration file. Usually I would shy away from the user variable in the bootstrap, which will be called every time the page is loaded, and then just refer to it as a global variable to other php files, this is what I would like to get in the bootstrap file.

$user = new User();

Then this is what I would have in the php calling file

global $user;
$user->foo();
0
source

All Articles