Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor versus too freaking many gets and sets

I have a record class with 18 properties.

Before that class can be submitted to the database, all 18 properties must have validated data.

Because I'm OOP-ifying a working procedural webapp, I went about this sort of backwards.

First I addressed workflow for modifying existing records. At the time, it made sense to throw all 18 properties into the __construct method and avoid craploads of setters. A separate loader class handles the dbase business and can return either single objects or an array of record objects. That all worked ok.

But then it came time to address the new record creation workflow, and suddenly I needed to instantiate an empty record, except my record constructor is a hungry beast that wants 18 parameters...

...so you strip the constructor? But then I'd have to add 18 setters and call them all each time I want to work with an existing record...

doesn't seem like much of an improvement! :-/

How do real programmers handle this? (I'm just a weenie hobbyist...)

like image 389
Drew Avatar asked Jan 18 '26 20:01

Drew


1 Answers

Either default arguments is one option, but then you have to fill out a large number of null's if you only want to use, say, the first and last.

Then again, you could do array looping:

private $prop1;
private $prop2;
// more properties here.

function __construct( array $props ) // `array` here is for type-hinting.
{
    foreach( array( 'prop1', 'prop2' /*, all of the props for this object */
             as $property )
    {
        // basically, this will assign all of the properties as they exist in the
        // props array
        if( isset( $props[ $property ] ) )
            $this->$property = $props[ $property ];
    }
}

Or, if you wanted to keep your old constructor signature:

function __construct( $prop1, $prop2 = NULL, $prop3 = NULL /* ... */ ) 
{
    if( is_array( $prop1 ) )
    {
         $this->array_prop_assignment( $prop1 );
    }
    else
    {
        $args = func_get_args();
        // this ensures that anything which is passed to the constructor
        // will go to the "new" old constructor
        call_user_func_array( array( $this, 'param_prop_assignment' ), $args );
    }
}

function param_prop_assignment( $prop1, $prop2 /* ... */ )
{
    //your old constructor can go here.
}

function array_prop_assignment( array $props )
{
    // foreach example above would go here.
}

The new version also gives you the option to simply:

$k = new DataClass(); // no idea what the real class name is.
$k->param_prop_assignment( 1, 2, 3 /* ... */ );
like image 123
cwallenpoole Avatar answered Jan 21 '26 12:01

cwallenpoole