I have a project in which I have implemented some kind of Entity - Repository pattern. Now in my I would like to know if it is OK have a special class just for the fields I have added an example at the bottom to what I mean. My motivation is:
-
Not to have the need to explicitly define the fields like in doctrine where you use annotations, Meta Data or even have array with strings of fields name that should be mapped to SQL table column
-
Make it easy to iterate only the fields that matter to the database
-
Ability to add properties that are not mapped to the database (like $maxPagePerBook in the example)
-
Have auto complete "naturally" without use of annotations
-
To have separation between the ID and the data fields
I think my example accomplish the goals above but I did not see examples of doing it that way. So I wonder if it might be an anti-pattern.
BTW I was not sure if to use the word "field" or "property" I tried to use the word field what the variable needed to be mapped to a database column and property when its a general property.
Would you create the special fields class or have better idea?
//// File BookEntity.php ////
class BookEntity
{
public $id;
/**
* @var BookEntityFields
*/
public $fields;
// For demonstrating the property that is needed but not mapped to database
public $maxPagePerBook = 400;
public function checkNumberOfPages()
{
if($this->fields->num_of_pages>$this->maxPagePerBook) return false;
else return true;
}
// $arr is usually a row from sql select query
public function loadFromArr($arr)
{
$this->fields = new BookEntityFields();
foreach($this->fields as $propName=>$value) {
$this[$propName] = $arr[$propName];
}
}
}
//// File BookEntityFields.php ////
// Inner class only to be used inside the BookEntity. Is it an anti pattern?
class BookEntityFields
{
public $publish_year;
public $num_of_pages;
public $author_name;
}
//// File BookController.php ////
// Just for demonstrating some action
class BookController
{
public function actionLoad($id)
{
// Dummy data
$row = array(['publish_year'=>1941,'num_of_pages'=>350,'author_name'=>'Foo Bar']);
$book = new BookEntity();
$book->loadFromArr($row);
if($book->checkNumberOfPages()){
return json_encode($book->fields);
}
else echo "error";
}
}
Aucun commentaire:
Enregistrer un commentaire