Selection database rows and treat them as object

107 views Asked by At

I'm developing a sort of "Model" in which I'd love to be able to select few rows (or just one) by the constructor and then be able to treat them as an object so for example, selecting all the posts that has "admin" as author with a limit of 10 would be:

$posts = new Post(array(
    'where' => array('author' => 'admin'),
    'limit' => array(0 => 10),
    # optional: 'order' => array($by => 'desc/asc')
));

# get a field
$id = $posts->row[0]['id'];

# editing fields
$posts->row[1]['body'] = 'new body';
$posts->row[2]['body'] = 'new body for post # 3';
$posts->update();

# delete all the selected posts
$posts->delete();

... et cetera.

But what I don't really like it the way it select the posts. It seems too mechanic and full of arrays in arrays that I don't really like. I also thought about "One object being one row" but this would take the require of 10 posts to perform 10 different queries. And that's not efficient.

Question #1 Is there a similar pattern or similar script that could inspire me? Am I the first one that think that database rows could be seen as PHP object (with all the pros that come along with this concept).

Question #2 Could be there another way of selecting multiple rows? Could be a solution to force the developer to specify only the primary key of a table (such as the post id) as selector? (<= I don't think this is a solution at all).

2

There are 2 answers

0
linepogl On BEST ANSWER

Most ORMs (Object-Relational Mappers) try to give answers to your question in one or another way.

I would suggest to have a look at Doctrine and at Propel to get ideas. Also, it would be good to see at other languages, such as Microsoft's LINQ for .NET.

Myself, I have recently published an ORM for PHP which is called Solid Oxygen. Have a look at the documentation, if you want. I believe that what I did is very close to what you try to develop.

0
Julien Bourdon On

Yes, some people have thought of that before. You have a plethora of PHP frameworks that handle database entries as objects. You could take a look to Code Igniter, CakePHP or Symfony. That is a personal opinion but I think that Code Igniter source code is easier to understand and that it could provide a good base to implement your whole object layer, if you still want to implement one after you realize how much a hassle it can be :)