I'm simply using Slim PHP MVC framework in my API project. PDO::FETCH_ASSOC is used in the database calls. So no data objects. The router handles requests and pass to the controller. controller calls the necessary model to do database operations and response is delivered.
This is the scenario that I want to handle different user types. Each user_type has user_type based specific db transaction to be done. I want to make this more reusable and remove code duplication.
Sorry if there's any wrong thing here, and for my English.
My Route
$this->post('/users/preferences', \UserPreferenceController::class . ':store')
UserPreferenceController => Controller
public function store($request, $response, $args){
$parsedBody = $request->getParsedBody();
$user_id = $parsedBody['user_id'];
$preferences = $parsedBody['preferences'];
$user = $this->User->getUserInfo($user_id);
if ($user["type_id"] == 'Admin') {
$preferenceAdded = $this->User->AddAdminUserPreferences($user_id, $preferences); // DB transaction operation
} else if ($user["type_id"] == 'Customer') {
$preferenceAdded = $this->User->AddCustomerUserPreferences($user_id, $preferences); // DB transaction Operation
} else if ($user["type_id"] == 'Sales') {
$preferenceAdded = $this->User->AddSalesUserPreferences($user_id, $preferences); // DB transaction Operation
}
// return if the transaction is rollbacked
if(!$preferenceAdded){
return $response->withJSON([
"error" => true,
"message" => "cannot add preferences for user"
"data" => $user_id
]);
}
if ($user["type_id"] == 'Admin') {
$staisticsAdded = $this->User->AddAdminUserPreferencesStatistics($user_id, $preferences); // DB transaction operation
} else {
$staisticsAdded = $this->User->AddOtherUserPreferencesStatistics($user_id, $preferences); // DB transaction operation
}
// return if the transaction is rollbacked
if(!$staisticsAdded ){
return $response->withJSON([
"error" => true,
"message" => "cannot add statistics for user"
"data" => $user_id
]);
}
return $response->withJSON([
"error" => false,
"message" => "operation completed successfully"
"data" => null
]);
}
User.php => User model
public function getUserInfo($user_id)
{
$sql = "SELECT id, name, email, type_id FROM users WHERE id= :id";
$stmt = $this->db->prepare($sql);
$result = $stmt->execute(['id' => $user_id]);
return $stmt->fetch()[0];
}
public function AddAdminUserPreferences($user_id, $preferences)
{
$this->db->beginTransaction();
try {
// $sql1 execute (common function for every user_type)
// rollback if $sql1 fails
// $sql2 execute (a user_type specific function)
// rollback if $sql2 fails
$this->db->commit();
return true;
} catch(\PDOException $e){
$this->db->rollBack();
return false;
}
}
My Container
$container = $app->getContainer();
$container['UserPreferenceController'] = function ($c) {
return new App\Controllers\UserPreferenceController($c);
};
$container['User'] = function ($c) {
return new App\Models\User($c);
};