2016-04-07 95 views
0

所以我建立了一個系統,現在我正在整理。我使用Codeigniter MVC框架和PHP Storm,在我看來,我有一大堆數學。見下圖。重構初學者

foreach ($records as $row) : 

      $join_date = $row->start_date; 
      $date1 = new DateTime('now'); 
      $date2 = new DateTime($join_date); 

      $p = $row->start_amount; 
      $i = $row->interest; 
      $c = 12; // compound frequency set to monthly 
      $n = ((int)$date1->diff($date2)->format("%m"))/12; 
      $r = $row->monthly_deposits; 
      $x = $i/$c; 
      $y = pow((1 + $x), ($n * $c)); 
      $Total_balance = $p * $y + ($r * (1 + $x) * ($y - 1)/$x); 

      $remain = 365 - $date1->diff($date2)->format("%a days"); 

      $Total_Deposits = ($row->monthly_deposits * (int)$date1->diff($date2)->format("%m")) + $row->start_amount; 
      $Total_Int = $Total_balance - $Total_Deposits; 

      $originalDate = $row->start_date; 
      $newDate = date("jS \of F Y", strtotime($originalDate)); 

      // Add field values to get row total 
      $rowTotal = $Total_balance; 

      // Add row total to grand total 
      $grandTotal += $rowTotal; 
      ?> 

我需要它,所以我可以調用我的代碼中的變量,它需要在循環中。

什麼是最好的辦法做到這一點,顯示我把數學模型和this>model>modelname在循環內?

感謝大家,代碼工作正常只是不確定最好的方法來保持整潔。

+2

爲什麼不直接將所有代碼直接放入模型的函數中,在控制器中調用該函數,並將它直接返回的數據發送到視圖。這個觀點不應該有那麼多的商業邏輯。 – Keeleon

+0

啊,這就是我在想的,謝謝。我會嘗試 – Beep

+0

加一個重構模型。 – cartalot

回答

0

視圖基本上是爲了顯示你已經計算出你的控制器。以此爲通用規則(並不意味着如果需要,您無法在模型或視圖上計算任何內容)。

爲了保持代碼的清潔和有意義的,我會做到以下幾點:

型號

class Random_model extends CI_Model { 
    function get_records() { 
     // access the database and return the rows you need 
    } 
} 

控制器

function whatever() { 
    $data = array(
     'first_result' => '', 
     'second_result' => '' 
    ); 

    $this->load->model('random_model'); 
    $records = $this->random_model->get_records(); 
    foreach ($records as $row) { 
     // do here the huge chunk of math and 
     // put in $data the results you need to display 
    } 
    $this->load->view('myview', $data) 
} 

查看

<div> <?php echo $first_result; ?> </div> 
<div> <?php echo $second_result; ?> </div>