3

私はコントローラーに次のコードを持っています:

<?php

class Student extends CI_Controller
{

function index()
{
    $data = $this->init->set();
    
    $this->parser->parse('include/header', $data);
    $this->parser->parse('student/student_index', $data);
    $this->parser->parse('include/footer', $data);
}

function planner()
{
    $data = $this->init->set();
    
    $this->parser->parse('include/header', $data);
    $this->parser->parse('student/student_cal', $data);
    $this->parser->parse('include/footer', $data);      
}

}
?>

ご覧のとおり、ここには多くの繰り返しがあります。基本的にすべてです。すでに変数をモデルに配置しているので、各関数の先頭に$ data配列全体を配置するのではなく、毎回モデル関数を呼び出すだけで済みます。とにかく、私は次のことを行うことによって、ここで繰り返しを減らしようとしました:

<?php

class Student extends CI_Controller
{

function index()
{
    $data = $this->init->set();
    
    $this->parser->parse('include/header', $data);
    
    switch($this->uri->segment(2))
    {
        case '': $this->home($data); break;
        case 'planner': $this->planner($data); break;
    }
    $this->parser->parse('include/footer', $data);
}

function home($data)
{
    $this->parser->parse('student/student_index', $data);
}


function planner($data)
{
    $this->parser->parse('student/student_cal', $data);
}

}
?>

これは、どういうわけか、私のホームページではうまく機能します。変数を解析し、何の問題もありません。ただし、「プランナー」ページでエラーが発生します。

メッセージ:Student :: planner()の引数1がありません

メッセージ:未定義の変数:データ

メッセージ:foreach()に無効な引数が指定されました

$data関数がどういうわけか配列を受け取らないので、私はこれらのエラーを受け取ると確信しています。また、CIドキュメントで、URLの3番目のセグメントが引数として渡されることを読みました。この場合、3番目のセグメントは存在しないため、何も渡されません。ただし、CIドキュメントでは、関数から関数に$data配列を渡す方法を教えてくれませんでした。また、なぜホーム機能がエラーなしで正常に機能するのか疑問に思います。index()planner()

4

2 に答える 2

3

さて、コードが本当に見づらくなるのであれば、そのリファクタリングの理由はわかりません。解析関数が何をするのか完全にはわからないので、それを変更した方法は、実際にパラメーターを文字列として渡すことでしたが、できればコンテンツをバッファーにロードして、その方法で渡します。しかし、ここにいくつかのよりクリーンでうまくいけば読みやすい重複のリムーバブルがあります...そしてうまくいけばそれは機能します:)。



class Student extends CI_Controller
{

  private function load_student_page($content){
      $data = $this->init->set();

      $this->parser->parse('include/header', $data);
      $this->parser->parse($content, $data);
      $this->parser->parse('include/footer', $data);

  }

  function index()
  {
    $this->load_student_page('student/student_index');
  }

  function planner()
  {
    $this->load_student_page('student/student_cal');
  }

}
于 2011-04-12T13:11:11.877 に答える
2

あなたが言ったように、CodeIgniterは3番目のセグメントをパラメーターとして渡そうとしていますが、それは存在しません。

「 _remap」関数を使用する必要がある場合があります。

class Student extends CI_Controller {

    public function _remap($method, $parameters)
    {
         $data = $this->init->set();
         $this->parser->parse('include/header', $data);

         switch($this->uri->segment(2))
         {
             case '': $this->home($data); break;
             case 'planner': $this->planner($data); break;
         }

         $this->parser->parse('include/footer', $data);
    }

}

于 2011-04-11T18:45:37.000 に答える