Transactional PDO with MVC on multiple models

I am creating a website and have several code segments for several models that must be executed inside a transaction, so if one of them does not work, the code will be rolled back.

Say I have a simple user registration form.

<form action="/register" method="POST">
        <div>
            <label for="username">Username</label>
            <input type="text" name="username" id="username" />         
        </div>
        <div>
            <label for="username">Password</label>
            <input type="password" name="password" id="password" />
        </div>
        <div>
            <label for="username">Email</label>
            <input type="text" name="email" id="email" />   
        </div>
        <div><input type="submit" name="submit" value="submit" /></div>
    </form> 

On my system, when a user is created, I need to automatically place them in roles.

To insert a User into the table, I use the User model. Then I need to insert a role table, which occurs in a separate model. If all the work that needs to be done is in separate models, where can I create a connection that will be transmitted through several models so that the transaction can work?

// Start Transaction.
// Create new user based on posted variables. UserModel
// Add user to a given role. UserRoleModel -> Table contains UserId and RoleId
// Commit transaction.

, , , ? db? , ? ?

+1
1

, :

Model

   1 DataBase  
     2  => UserTableDefinition  
             3  =>  UserDefaultInteraction 
                    4   => UserCustomFunctions  
                           5 =>  UserOuterLayer

. (5);

, yuou , , . :

class UserOuterLayer extends UserCustomFunctions {

    public function createNewUser ($data) {
       // create a new user from array
        $user = new self();
        $user->setName($data['name']);
        $user->setUserName($data['username']);
        $user->setPassword($data['password']);
        $user->setRole($data['role']);

       if ($user->save()) { // when the object is saved it assign a new value for $user->id
            $role = new UserRole(); // accessing another model
            $role->setUserId($user->getId()); // returns the new id from the saved object
            $role->setRole($user->getRole());
            $role->save();
       }    
    }
}

, , :)

0

All Articles