r/PHPhelp • u/silentheaven83 • Jun 17 '23
Understanding Array vs Object
Hello everybody,
sorry if it's a dumb question but I need your help.
Between these two solutions for saving a Book after a form submit:
// book_submit.php
$BookMapper = new BookMapper(
$Database,
$Log
);
$Book = new Book();
$Book->title = $_POST['title'];
$Book->summary = $_POST['summary'];
$BookMapper->insert($Book);and
// book_submit.php
$BookMapper = new BookMapper(
$Database,
$Log
);
$BookMapper->insert(
array(
"title" => $_POST['title'],
"summary" => $_POST['summary']
)
);
// Or even
$BookMapper->insert($_POST);which one is considered the best and why?
The BookMapper class will return a Book object from its select() method, here I'm only talking about saving data.
Thank you
9
Upvotes
2
u/[deleted] Jun 17 '23
Normally you would prefer the first method (basically a very basic ORM or object relationship mapping pattern, where you associate a database table and it's relations with an object in PHP). You define your common used database objects (entities) as classes and use instances of them to contain informations. Objects have the big advantage that you can ensure that all required informations are there, you can enforce types and can define additional logic in the form of functions on it. However instead of directly accessing the fields of the class, you would normally encapsulate them via setX and getX functions, so you can control Access to them (check for allowed values and so on).