lundi 9 novembre 2015

What design pattern do I use when I need to call a helper function before I create an object?

I have a class Motor, which I use to provide me with various motor specifications.

I currently have the following methods as part of the Motor class:

public function getIdFromModel($model)
{
    $sql = "SELECT id FROM ... WHERE model = ...";
    return process($sql);
}

public function getIdByFrame($size)
{
    $sql = "SELECT id FROM ... WHERE size = ...";
    return process($sql);
}

The above are supplementary functions used to get motor's id from database, when some other non-id parameter is known. id is then used to create the actual motor.

Before I could do:

$model = "ABC";
$motor = new Motor();

//retrieve ID
$id = $motor->getIdFromModel($model)

$motor-loadSpecs($id);
$motor = new Motor($id);

My problem shows up after I have changed the structure of my class to require knowledge of id at Motor creation time. Now I need to do:

$model = "ABC";

//retrieve ID
$id = $???->getIdFromModel($model)

$motor = new Motor($id);

Question

What structure/class/pattern/function do I use in place of ??? above?

I know that I can create a class just for the above two functions, but I feel there is a better answer/pattern for this and I wanted to ask. I don't see a meaning for creating a class just for something-to-id methods. I'd like to have some meaning.

Aucun commentaire:

Enregistrer un commentaire