Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to properly load a Database row into a class in php
    primarykey
    data
    text
    <p>I am using Kohana 3.2, not that it matters much, but I am writing an application where I am wrapping any and all returned database records in a specific class. I don't know that I understand the best way to load the database row into the class, because sometimes it is a ORM model and sometimes it might just be an row ID. </p> <p>So from a controller if I wanted a list of all the users it would look something like:</p> <p>Controller:</p> <pre><code>$users = User::find_all(); </code></pre> <p>User Class</p> <pre><code>public static function find_all() { $users_model = ORM::factory('user')-&gt;find_all(); $users = array(); foreach ($users_model as $user_model) { $users[] = User::instance($user_model); } return $users; } </code></pre> <p>That works great, but sometimes I need to load a user object with just an id, like after some action, again a example:</p> <p>Controller</p> <pre><code>$user_id = $_POST['user_id']; $user = User::instance($user_id); </code></pre> <p>So is the User class responsible for trying to identify if an ID or a ORM object was passed into it. It seems like that isn't right for good OOP practices, but I am really not sure what the best way to do it is. What I have been currently doing is in the construct:</p> <pre><code>public function __construct($user, $load = 'model') { if ($load == 'model') { $this-&gt;user_model = $user; } if ($load == 'id') { $this-&gt;user_model = ORM::factory('user', $user); } } </code></pre> <p>But that really just doesn't feel right. Any advice would be greatly appreciated.</p>
    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.
    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