0

次のコードをpublicの下のすべてのコントローラーに配置しますfunction index()。現在、私は3つのコントローラーを持っており、Webサイトが完成するまで増加します。すべてのページ(つまりビュー)に以下のコードが必要です。

$type = $this->input->post('type');
$checkin = $this->input->post('sd');
$checkout = $this->input->post('ed');

私の質問は、上記のコードを1つの場所に配置して、すべてのページ(つまり、ビュー)で使用できるようにし、すべてのコントローラーに配置しないようにすることができるかどうかです。

4

3 に答える 3

0

idは提案し、それをライブラリに追加してからライブラリを自動ロードして、Webサイトのすべてのページが同じにアクセスできるようにします。

refferの自動ロードの場合:codeigniterでの自動ロード

于 2012-08-17T09:29:44.970 に答える
0

CI_controllerを拡張する独自のコントローラー(MY_cotrollerなど)を作成し、そこに共有コードを配置すると、3つのコントローラーがMY_controllerを拡張する必要があります。その後、必要な場所で呼び出すことができます(または、必要な場合はコンストラクターに配置することもできます)。

これが私が約束したサンプルです(デフォルトのcodeigniter設定があると仮定します)

コアフォルダにMY_Controller.phpという名前のファイルを作成します

class MY_Controller extends CI_Controller{

   protected $type;
   protected $checkin;
   protected $checkout;

   protected $bar;

     public function __construct()
    {
        parent::__construct();
        $this->i_am_called_all_the_time();
    }

    private function i_am_called_all_the_time() {
       $this->type = $this->input->post('type');
       $this->checkin = $this->input->post('sd');
       $this->checkout = $this->input->post('ed');
    }

    protected function only_for_some_controllers() {
       $this->bar = $this->input->post('bar');
    }

    protected function i_am_shared_function_between_controllers() {
       echo "Dont worry, be happy!";
    }
}

次に、コントローラーフォルダーにコントローラーを作成します

class HelloWorld extends MY_Controller {

    public function __construct() {
       parent::__construct();
    }

    public function testMyStuff() {
       // you can access parent's stuff (but only the one that was set), for example:
       echo $this->type;

       //echo $this->bar; // this will be empty, because we didn't set $this->bar
    }

    public function testSharedFunction() {
       echo "some complex stuff";
       $this->i_am_shared_function_between_controllers();
       echo "some complex stuff";
    }
}

次に、たとえば、別のコントローラー:

class HappyGuy extends MY_Controller {

    public function __construct() {
       parent::__construct();
       $this->only_for_some_controllers(); // reads bar for every action
    }

    public function testMyStuff() {
       // you can access parent's stuff here, for example:
       echo $this->checkin;
       echo $this->checkout;

       echo $this->bar; // bar is also available here
    }

    public function anotherComplexFunction() {
       echo "what is bar ?".$this->bar; // and here
       echo "also shared stuff works here";
       $this->i_am_shared_function_between_controllers();
    }
}

これらは単なる例であり、もちろんこのようなものをエコーすることはありませんが、表示などに渡すことはできますが、説明には十分だと思います。誰かがより良いデザインを持っているかもしれませんが、これは私が数回使用したものです。

于 2012-08-17T06:01:01.197 に答える
0

たとえば、メイン ビュー ファイルがあり、すべてのページでそのコードが必要な場合は、メイン ビュー ファイル (view/index.php) に配置することをお勧めします。

@KadekMの回答では、すべてのコントローラーで毎回関数を呼び出す必要があると思います。悲しいことに、すべてのコントローラーですべての関数にこのコードが必要だからです。

于 2012-08-17T07:21:10.047 に答える