Classes of collection of objects or not.

I am trying to decide whether to create many classes for each type of content that I have in my application / database, or just stick to the procedural code.

Version 1:

  • create a class for each set of objects:

    class App{ protected $user_collection; function getUserCollection(){ if(!isset($this->user_collection) $this->user_collection = new UserCollection($this); return $this->user_collection; } // ... } class UserCollection{ function __construct(App $app){ $this->app = $app; } function getUser($user){ return new User($this->app, $user); } function getUsers($options){ $users = $this->app->getDatabase()->query($options); foreach($users as &$user) $user = new User($this, $user); return $users; } // ... } 

which I use as:

 $app = new App(); echo $app->getUserCollection()->getUser('admin')->email_address; 


version 2:
  • save all methods in one class

     class App{ function getUsers($options){ $users = $this->getDatabase()->query($options); foreach($users as &$user) $user = new User($this, $user); return $users; } function getUser($user){ return new User($this, $user); } // ... } 

used as:

 $app = new App(); echo $app->getUser('admin')->email_address; 


version 3:
  • Make getUsers () a static method in the User class (the method creates a new User object):

     $app = new App(); echo User::getUser($app, 'admin')->email_address; 

Which direction should I go? The "user" object is just an example, the application has other objects, such as a "database", "pages", etc.

+4
source share
2 answers

Personnaly, I often used the second method with this method:

 class user { /** * Load object from ... */ public function load($userId) {} /** * Insert or Update the current object */ public function save() {} /** * Delete the current object */ public function delete() { // delete object // Reset ID for a future save $this->UserID = null; } /** * Get a list of object */ public static function getList() { // Make your search here (from DB) // Put rows into new "SELF" object $list = array(); foreach($rows as $row) { $obj = new self(); $obj->populate($row); $list[$obj->UserID] = $obj; // Associative array or not... } } } 

As you can see, I set my getList static function to easily access this:

 $listUsers = user::getList(); 

OK, this is very simple, but in most cases a simple application works.

+1
source

I would use your version 1, but I would make the getUser () and getUsers () methods of the application. This eliminates the inconvenient call to getUserCollection (), because instead, getUser () is inside it and that you just don't call $ this-> user_collection.

+2
source

Source: https://habr.com/ru/post/1403466/


All Articles