【问题标题】:Store persistent value in model (PHP, MVC)在模型中存储持久值(PHP、MVC)
【发布时间】:2015-10-26 21:23:19
【问题描述】:

我正在做一个 PHP 代码点火器的测验。我正在尝试使用一个函数来增加每个正确答案的分数。 目前我没有向视图传递任何东西,我在控制器中有这个:

if ($res == true)
        {
        $scoreIncrement = 1;    
        $scoreResult = $this->Starmodel->increment($scoreIncrement);
        var_dump($scoreResult);

如果问题是正确的,我将值 1 传递给函数增量,并且我正在转储结果以查看我得到了什么。 这是我在模型中的功能:

var $score; //variable to hold the total score.

function increment($increment){

        $this->score = $this->score + $increment;
        return $this->score;
}

当我每次运行应用程序时,我总是从 var_dump 获得 1。 变量 var $score; 是否在模型中持久存在? 我也点击下一步,这意味着我正在加载显示新消息的功能,也许这正在重置结果。如何在模型中有一个变量来保存当前分数? 谢谢

【问题讨论】:

    标签: php codeigniter model-view-controller


    【解决方案1】:

    使用会话。

    您似乎没有意识到您对每个答案都调用了一个新的 PHP 进程。

    PHP 一遍又一遍地从表单中的每个帖子或通过 href 的请求开始。

    每次请求都会重新初始化您的内部数据,因此会产生结果。

    查找会话以实现请求之间的持久性。

    http://php.net/manual/en/features.sessions.php

    【讨论】:

      【解决方案2】:

      您可以使用 SESSIONS 或 COOKIES 来实现所谓的“数据持久性”

      http://php.net/manual/en/features.cookies.php

      Setting new cookie
      =============================
      <?php 
      setcookie("name","value",time()+$int);
      /*name is your cookie's name
      value is cookie's value
      $int is time of cookie expires*/
      ?>
      
      Getting Cookie
      =============================
      <?php 
      echo $_COOKIE["your cookie name"];
      ?>
      

      【讨论】:

        【解决方案3】:

        您还可以将当前分数放在隐藏的表单字段中

        // in your view form 
        echo form_hidden('currentscore',$this->score); 
        

        然后在表单提交后取值

        // pass to your method to increase the score
        $currentscore = $this->input->post( 'currentscore') ; 
        
        $score = $currentscore + 1 ; 
        

        观点:使用 $this-> 确实很强大,但它可能会变得笨拙。如果您需要将值传递给模型中的方法,请考虑明确地执行此操作。

        function incrementScore($increment,$score){
        
                $scoretotal = $increment + $score;
                return $scoretotal;
        }
        

        【讨论】:

          猜你喜欢
          • 2012-03-03
          • 2014-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-14
          • 2012-08-13
          • 1970-01-01
          相关资源
          最近更新 更多