User design

Hi, I’m looking for any tips or comments on the following design:


class User {
  public function isLoggedIn(){}
  public function isStaff(){}
  public function getEmail(){}
  public function createUser() {}
  //etc..
}

class UserAction {
  private $user;
  public function __construct(User $user) {
    $this->user = $user;
  }

  public function emailAdmin() {}
  public function postNewMessage() {}
}

//or DI through each method? First example of UserAction is more convenient imo.
//but less abstract than the second example:

class UserAction {
  public function __construct() {}
  public function emailAdmin(User $user) {}
  public function postNewMessage(User $user) {}
}

Thanks :slight_smile:

I would do this:


class User {
  public function isLoggedIn(){}
  public function isStaff(){}
  public function getEmail(){}
  public function createUser() {}
  //etc..
}

class UserAction {
  public static function emailAdmin(User $user) {}
  public static function postNewMessage(User $user, Thread $thread) {}
}

Since your UserAction actions only need the $user object to work their magic, nothing else.

Stuff like DB connections and so on, I usually have them linked to the $user object.

This makes unit testing very simple and easy (test one function at a time, with some mock up User objects)

Well I don’t know what you want to hear, a simple interface like that will not result in much conversation.

Constructor injection is usually favored among professionals, it means doing it once at the time of construction, which is where it would normally done if using classical composition anyways.

I can’t even comment on dependencies. UserAction class appears to be some form of model? User class is possibly a DAO or some similar pattern.

Injecting the DAO into the model means you can more easily test the model by mocking the DAO, however it also possibly means, having to inject the DAO into every single model. Scattering your connection details all over the place in the controllers leads to horrible code, IMO. You might alleviate much of that using a DiC, or a simple wrapper I suppose.

Cheers,
Alex