Note that there are some explanatory texts on larger screens.

plurals
  1. POCould someone give a perfect example of a basic "user" object system, using PDO?
    primarykey
    data
    text
    <p>What I'd like is to see the ideal framework for a system which has a group of objects (ie User) whereby the data is contained in a database. I've been advised to have a User class and a UserMapper class and this is my understanding of how it should look:</p> <p><strong>user.class.php</strong> <pre><code>/* The class for constructing any user's information */ class User { protected $userId, $email, $userGroup; protected function getEmail() { return $this-&gt;email; } protected function getUserId() { return $this-&gt;userId; } public function __construct($userId, $email, $userGroup) { $this-&gt;userId = $userId; $this-&gt;email = $email; $this-&gt;userGroup = $userGroup; } } class UserMapper { // database connection private $db; public function __construct($db) { $this-&gt;db = $db; } public function findByUserId ($userId) { $userObject = new User(); $q = $this-&gt;db-&gt;prepare("SELECT userId, email, userGroup FROM user WHERE userId = :userId"); $q-&gt;bindValue(":userId", $id); $q-&gt;setFetchMode( PDO::FETCH_INTO, $userObject); $q-&gt;execute(); $q-&gt;fetch(PDO::FETCH_INTO); return $userObject; } } ?&gt; </code></pre> <p><strong>main.php</strong></p> <pre><code>&lt;?php include user.class.php; $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT =&gt; true)); $getUser = new UserMapper($dbh); $user = $getUser-&gt;findByUserId(41); echo $user-&gt;getEmail(); ?&gt; </code></pre> <p>But this seems a bit messy in terms of the main.php side. Can I not make one PDO object and have that defined in all of my scripts? As well as a UserMapper object? Or do every time I want to get a user from the database do I need to make a NEW userMapper object, then do findByUserId (as above). Or is there a simpler way to doing this? </p> <p>If I wanted to call a UserGroup object within the class User, how would I do this? (This would also need to connect to the database through PDO). To do the following seems messy:</p> <pre><code>&lt;?php $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT =&gt; true)); $getUserGroup = new UserGroupMapper($dbh); $userGroup = $getUserGroupMapper-&gt;findByUserId($this-&gt;userGroup); ?&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload