So I've been researching and working on building my own MVC framework but keep running into 6 different ways of implementing it and I'd like to know if I'm on the right track with what I have so far. And yes, I know I could use Zend or others like it but I really want to learn how frameworks work and not just use someone else's.
Here is a simple version of my index file:
if(isset($_GET['url']))
{
$url = strtolower($_GET['url']);
}
else
{
$url = 'home';
}
switch($url) // Select the controller based on the GET var in the url
{
case 'home': include(ROOT_DIR . 'app/controllers/homeCon.php'); // This page has the link to the DB test page on it
break;
case 'dbtest': include(ROOT_DIR . 'app/controllers/dbTestCon.php');
break;
default: include(ROOT_DIR . 'app/views/error404View.php');
}
Here is a simple version of my dbTestCon.php controller:
if(isset($_POST['dbSubBtn']))
{
$model = new DbTestModel();
if($_POST['firstName'] != '' && $_POST['lastName'] != '')
{
$model->submitToDb($_POST['firstName'], $_POST['lastName'])
$model->displayPage('goodToGo');
}
else
{
$model->displayPage('noInput');
}
}
else
{
$model->displayPage('normal');
}
Here is my DbTestModel.php:
class DbTestModel
{
public function displayPage($version)
{
$title = "DB Test Page";
$themeStylesheetPath = 'public/css/cssStyles.css';
include(ROOT_DIR . 'app/views/headerView.php');
include(ROOT_DIR . 'app/views/dbTestView.php');
switch($version)
{
case 'goodToGo':
include(ROOT_DIR . 'app/views/dbTestSuccessView.php');
break;
case 'noInput':
include(ROOT_DIR . 'app/views/noInputView.php');
break;
}
include(ROOT_DIR . 'app/views/footerView.php');
}
public function submitToDb($firstName, $lastName)
{
try
{
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db->prepare('insert into dbtest(firstName, lastName) values(:firstName, :lastName)');
$sql->bindParam(':firstName', $firstName);
$sql->bindParam(':lastName', $lastName);
$sql->execute();
$db = null;
}
catch(PDOException $e)
{
echo "It seems there was an error. Please refresh your browser and try again. " . $e->getMessage();
}
}
}
And here is my dbTestView.php:
<form name="dbTestForm" id="dbTestForm" method="POST" action="dbtest">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" />
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" />
<input type="submit" name="dbSubBtn" id="dbSubBtn" value="Submit to DB" />
</form>
This simple example works in my testing environment but I'm worried I'll start using it on my next project and realize half way into it that there is something fundamentally wrong with my framework and have to start over again. Thank you for any help or advice.