I’m trying to decide whether to create many classes for each content type I have in my application/database or just stick with procedural code.
Version 1:
-
make a class for each object collection:
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’m using like:
$app = new App();
echo $app->getUserCollection()->getUser('admin')->email_address;
version 2:
-
keep all methods in a single 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 like:
$app = new App();
echo $app->getUser('admin')->email_address;
version 3:
-
make getUsers() a a static method in the “User” class (the method instantiates a new User object):
$app = new App(); echo User::getUser($app, 'admin')->email_address;
Which way should I go? The “user” object is just an example, App has other objects too, like “database”, “pages” etc.
Personnaly, I often used the second one with method like this:
Like you can see, I set my “getList” function static to simply access like this:
OK, it’s very simple but work in most case of simple app.