访问模型中的post vars或通过视图中的函数调用传递它们?

时间:2012-10-09 01:36:09

标签: php model-view-controller

因此,在使用我自己的家庭构建的MVC框架进行修补时,我注意到需要进行一些重构的内容。

如果我在视图中有一个函数调用,它调用驻留在模型中的函数,并且该函数需要session / post / get vars for parameters。最好在函数调用中将这些变量作为参数传递,或者只是在模型中的函数中访问它们?

视图中的代码:

$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 ?>

模型中的代码:

// 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); 
    }
}

我问的原因是因为将参数放在视图中的函数调用中会使视图看起来很重,但是以另一种方式执行它,访问模型中的session / get / post vars,看起来有点hacky并且会使代码不是很可重用。谢谢你的建议!

1 个答案:

答案 0 :(得分:2)

解决方案是:解耦

基本上,传递函数调用中的POST变量。

为什么呢?因为逻辑将保持分离(控制器将使用它所需的任何部分请求然后将调用模型),并且它将更容易测试(您将能够传递假参数而不是伪造{{1} }和$_POST变量或做一些其他奇特的事情)。它也更容易调试。

换句话说,脱钩会使你的工作变得轻松。