So while tinkering around with my own home built MVC framework I noticed something that looked in need of some refactoring.
If I have a function call in the view that calls a function residing in the model and that function takes session/post/get vars for parameters. Is it best to pass those vars as arguments in the function call or just access them in the function that’s in the model?
Code in the view:
$model = $this->model; // Shortcut to the model
$vaildator = $this->model->validator; // Shortcut to the Validator object in the model
$btnPressed = $this->model->btnPressed; // Shortcut to the btnPressed flag var in the model
<label for="firstName">First Name: <span class="<?php echo $model->setReq($_POST['firstName'], 'First name'); // Set the class of the span tag the holds the 'required' text ?>">(required)</span></label>
<input type="text" name="firstName" id="firstName" title="First name" value="<?php echo htmlspecialchars($btnPressed ? $_POST['firstName'] : 'First name'); // Echo the user's entry or the default text ?>" maxlength="50" />
<?php if($btnPressed) $vaildator->valName($_POST['firstName'], true, true, 'First name'); // Check for errors and display msg if error is found ?>
Code in the model:
// If the field is empty or still contains the default text, highlight the 'required' error msg on the input field by changing the msg's class
// Note: used only for input fields that are required
public function setReq($postVar, $defaultText)
{
$className = 'required';
if($this->btnPressed)
{
$className = $postVar == '' || $postVar == $defaultText ? 'reqError' : 'required';
return htmlspecialchars($className);
}
else
{
return htmlspecialchars($className);
}
}
The reason I ask is because putting the arguments in the function calls in the view makes the view seem logic heavy but doing it the other way, accessing session/get/post vars in the model, seems a bit hacky and would make the code not very reusable. Thanks for any advice!
The solution is: decoupling.
Basically, pass the POST variables in the function call.
Why? Because the logic will stay separated (the controller will use whatever part of request it needs and then will call model), plus it will be a lot easier to test (you will be able to just pass fake arguments instead of faking
$_POSTand$_GETvariables or doing some other fancy things). It will also be easier to debug.In other words, decoupling will ease your work.