tags:

views:

29

answers:

1

I'm working on a PHP web app and I'm trying to use the MVC model. I have a lot of things that exist as 'database entities' -- a row, or a set of related rows, that are conceptually one human recognizable 'thing'. So I often try to provide an interface to that thing in a model class.

So of course, the run of the mill functionality is to have an existing entity, get some data from it, and sometimes update it. However, where I run into problems is when I need to create a new entity. None of the default data for an existing entity exists yet!

For instance, my __construct() methods will often have arguments (i.e. $id for WHERE id = $id) so that I can select data from the database and populate all the properties of the object from that data. However, when I want to create a new entity, the values for those arguments don't exist yet!

How do you all handle this situation? Do you

  • try to provide functionality for both creation and subsequent manipulation in the same object
  • have another class just for generating the entity
  • avoid __construct and have somthing like create() for new entities and instantiate() for existing ones
  • something else?
+2  A: 

If you need the ability to create "new" objects, then I don't think your constructors should be loading from the database by default. Since PHP doesn't support function overloading (so you can't have overloaded constructors), you can either just remove the "populate from database" code from the constructor into a function for that purpose, or give the $id-type argument a default value that indicates that properties shouldn't be populated from the database:

function __construct($id = 0)
{
    if ($id == 0)
        // create with blank properties
    else
        // load from database
}

Then if you want a new object, you just call it with no arguments, and if you want to load from the database, you include the id argument.

Chad Birch