问题很简单: 如何将数据从模型传递到视图(或返回控制器)以显示“密码太短”等错误
class UsersController extends Controller {
private $username;
private $password;
function register()
{
if($_POST)
{
$this->User->username = $_POST['username'];
$this->User->password = $_POST['password'];
$this->User->register();
}
}
}
class User extends Model {
public $username;
public $password;
function register()
{
$username = $this->username;
$password = $this->password;
if (!empty($username) && !empty($password))
{
// registration process
}
else
{
// "you must provide a username and password" or something like that
}
}
答案 0 :(得分:1)
只需将模型register
中的return "PASSWORD";
函数放到控制器中,让控制器从模型中返回并将其返回到视图中。让视图解释“PASSWORD”的错误输出是什么。
示例:
class UsersController extends Controller {
private $username;
private $password;
function register()
{
if($_POST)
{
$this->User->username = $_POST['username'];
$this->User->password = $_POST['password'];
return $this->User->register();
}
}
}
class User extends Model {
public $username;
public $password;
function register()
{
$username = $this->username;
$password = $this->password;
if (!empty($username) && !empty($password))
{
// ...
return "SUCCESS";
}
else
{
return "PASSWORD";
}
}
}
$responses = array("SUCCESS" => "Registered Successfully!", "PASSWORD" => "You must provide a username and password!");
$result = $this->UsersController->register();
echo $responses[$result];
答案 1 :(得分:1)
只需让你的模型方法返回一个值,或抛出异常,就像任何常规方法一样。然后在控制器中处理它。视图不应直接从模型触摸数据,这是控制器的工作。
答案 2 :(得分:0)
public function addAction()
{
$form = $this->_getForm();
$this->view->form = $form;
$this->render('add', null, true);
}
public function editAction()
{
$id = $this->getRequest()->getParam(0);
$Model = DI::get('yourclass_Model');
$form = $this->_getForm();
$data = $Model->getData();
$form->populate($data);
$this->view->flashMessages = $this->_helper->FlashMessenger->getMessages();
$this->view->form = $form;
$this->render('add', null, true);
}
public function saveAction()
{
$form = $this->_getForm();
$Model = DI::get('yourclass_Model');
try{
$saved = $Model->saveForm($form, $_POST);
} catch (Exception $e) {
echo "<pre>";
print_r($e);
exit;
}
if($saved)
{
$this->_helper->FlashMessenger('Record Saved!');
$this->_redirect("edit".$form->id->getValue(), array('exit'=>true));
}
$this->view->errorMessage = 'There were some errors';
$this->view->form = $form;
$this->render('add', null, true);
}
答案 3 :(得分:-2)
创建一个实现Singleton模式和ArrayAccess接口的类。 或者使用依赖注入创建类似的东西。
最终的解决方案是创建一些验证架构。 (模型验证其自身,并且视图中提供了错误状态。)