BaseModel - Rails style model extension |
[eluser]beaufrusetta[/eluser]
So, I figured I'm at a point where I can actually share this - if not, I'll never get any feedback and how am I supposed to forge forward and make this class better? So any who - here it is - BaseModel Basically, your models should control all the interaction with your database tables. When working with Ruby on Rails, there are a lot of things already taken care of for you - creating/updating/deleting/finding/etc. Drop the class in to your application/libraries dir and just make sure you load the library when you need it or have it available all the time by just autoloading it. Defining a Model Code: class User extends BaseModel { Inside the parent::__construct() call, you pass in the ID or FALSE, and you pass in the name of the table that the model maps to. Simple enough. Basic Loading via Primary Key Code: $user = new User(123); Loading via find_by (unique field) Code: $user = new User; The "find_by" syntax is similar to rails and maps to the fields on your table. If you want to find a record by gadget_number (and load the model with its data) you would do it like this: Code: $gadget = new Gadget; Creating Records Code: $user_data = array("email" => "[email protected]", "pass" => md5('OMGHI2UBBQ')); By passing in an associative array with field names as the keys, you can easily drop in values. To make this stupid simple from a form, I use the following technique: Code: <form> Ok - that's super simple, but you get the point - then that does a POST: Code: $user = new User; Clearly you want to put some checks in there, but that's the basics of that. Updating Single Attribute Code: $user = new User(123); Updating Multiple Attributes Code: $updates = array("first_name" => "Tim", "last_name" => "Dog"); Destroying Code: $user = new User(123); Relationships & Spawning You can setup relationships between other tables using this model library as well. Code: class User extends BaseModel { When doing this, you will now have an attribute "dogs" and "family" to access in your object. "dogs" will be an array of "dog" objects, and "family" will be singular. These will AUTOMATICALLY LOAD when you create the object. When it spawns, it won't spawn down on an object it spawned up on, but it will spawn up inside objects it has spawn down in to. I'm working on a fix for that - because if it's coming from an upper object, it's just wasting resources at that point. Ummm...I've got some more goodies in there - like mucking with the primary key if it's not "id", etc. Please leave me some feedback, comments, questions, flames, etc...I don't mind. |
Welcome Guest, Not a member yet? Register Sign In |