I’ve fairly new to PHP MVC and I’m not 100% sold I’m doing this in the most logical way possible. This is a piece of code from one of my controllers. A friend said a majority of this code should be moved into the Model? Is this so?
Right now I have a DataAccess layer that does all the SQL work. For User work I have a UserDataAccess object, which will create, update and delete. It appears I’m using something along the lines of the Data Mapper pattern. My Model classes map directly to the database columns on a given table and that’s it.
I’m continually confused at where each piece of code should go.
// Posted values passed all checks.
if(count($errors) == 0)
{
try
{
// Get a Connection.
$connection = ConnectionFactory::GetConnection('mysql');
try
{
$connection->beginTransaction();
// Create DataAccess object.
$uda = new UserDataAccess();
// Check if username and email are avail.
if(count($uda->CheckUsername($connection, $user->Username)) > 0)
$errors['username_taken'] = "Username is taken";
if(count($uda->CheckEmail($connection, $user->Email)) > 0)
$errors['email_taken'] = "Email is taken";
if(count($errors) == 0)
{
// Perform Create.
$userId = $uda->CreateUser($connection, $user->GetArray());
// Add User to Rookie Role.
$uda->AddUserToRole($connection, 1, $userId);
// Commit connection.
$connection->commit();
}
// Clear connection.
$connection = null;
// Redirect user.
if(count($errors) == 0)
header('location: /' . $user->Username);
}
catch(PDOException $e)
{
$connection->rollBack();
$errors['internal'] = "Opps: There was an error processing the request.";
}
}
catch(Exception $e)
{
$errors['internal'] = "Opps: There was an error processing the request.";
}
}
}
From the looks of it, it seems like some code that sound go into the controller.
Here’s a break down of MVC:
That probably sounded really abstract. The general idea of views is that they are the HTML template, with minimum codes, preferably only echoing certain dynamic element of the page (NOT THE HTML, just plain text, usually) and/or a bit of if and foreach loops. Example:
The idea behind controllers is how you get your page to actually work, by handling the logic, getting input, and such. Example:
Granted that the above is only a simple example, you get the point. The
render()renders the page and passes thekey => valuepair in the array so that the view has access to them.The Model is the database interaction. It allows you to access the database without using SQL (preferably). Example:
So Models don’t have to have the most coding. In my opinions controllers would have a lot of code, but that totally depends on the complexity of what you’re building.
Hope that clears it up for you.