如何从模型发送多条消息到视图?

How to send multiple messages from model to view?

在我的模型中有一些自定义错误消息。

这只是我的代码的一部分:

if (!array_key_exists($target, $this->errors)) {
    $this->errors = [ $target => '<div class="alert alert-danger" role="alert">Sorry, we could not connect to your <strong>'. $target .' database</strong>. Plese check your entries and try connecting again.</div>' ];
}

// There is no connection. Display the right error message and return null
if (count($this->errors > 0)) {
    if (count($this->errors == 0)) {
        echo array_values($this->errors)[0];
    }
    elseif (count($this->errors == 1)) {
        echo '<div class="alert alert-danger" role="alert">Sorry, we could not connect to both of your databases. Plese check your entries and try connecting again.</div>';
    }
    elseif (count($this->errors > 1)) {
        echo '<div class="alert alert-danger" role="alert">Warning: There is an unknown error. For more information please contact the owner of this website.</div>';
    }
    return null;
    echo '<Form Layout>';
}
else {
    return $this->result;
}

我实际上并不想在我的模型中回显这些错误消息。那么将它们发送到视图的最佳方式是什么?

<?php
if (!array_key_exists($target, $this->errors)) {
    $this->errors = [ $target => '<div class="alert alert-danger" role="alert">Sorry, we could not connect to your <strong>'. $target .' database</strong>. Plese check your entries and try connecting again.</div>' ];
}
$aResult[ 'data' ]   = '';
$aResult[ 'errors' ] = '';
// There is no connection. Display the right error message and return null
if (count($this->errors > 0)) {
    if (count($this->errors == 0)) {
        $aResult[ 'errors' ][] = array_values($this->errors)[0];
    }
    elseif (count($this->errors == 1)) {
        $aResult[ 'errors' ][] = '<div class="alert alert-danger" role="alert">Sorry, we could not connect to both of your databases. Plese check your entries and try connecting again.</div>';
    }
    elseif (count($this->errors > 1)) {
        $aResult[ 'errors' ][] = '<div class="alert alert-danger" role="alert">Warning: There is an unknown error. For more information please contact the owner of this website.</div>';
    }
    $aResult[ 'errors' ][] =  '<Form Layout>';
}
else {
    $aResult[ 'data' ] = $this->result;
}
return $aResult;

// Then check if $aResults[ 'errors' ] is empty and handle as needed.
?>

正如@Vladimir Ramik 回答的那样,您可以 return 错误数组,这样您就可以从控制器调用方法并将其保存在变量中

$this->load->model('modelName');
$x = $this->modelName->method(); // this will hold your error array

如果您不想 return 数组(尽管我相信它是最好的),您可以使用 get_instance() 函数将模型中的数组直接保存到控制器数组中。

在您的模型中:

function methodName() {
    $CI = get_instance();

    $CI->errors[] = 'error message';
}

在你控制器

function fn() {
    $this->load->model('modelName');

    $this->modelName->methodName();

   // after we run the method in the model, we have here in the controller an array named errors.
   // it is best to declare the array on the begining of the class as public errors = array

   var_dump($this->errors);
}