0

我将以下代码放在 public 下的每个控制器中function index()。到目前为止,我有 3 个控制器,它会增加,直到我的网站完成。我需要所有页面(即视图)中的以下代码。

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

我的问题是我在哪里可以将上面的代码放在一个位置,这样它就可以在所有页面(即视图)上使用,并且避免将它放在每个控制器中。

4

3 回答 3

0

您可以创建自己的控制器(例如 MY_cotroller)扩展 CI_controller,将共享代码放在那里,然后您的三个控制器应该扩展 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 回答
0

id 建议,将其添加到库中,然后自动加载库,以便您网站上的每个页面都可以访问相同的页面。

用于自动加载参考:codeigniter中的自动加载

于 2012-08-17T09:29:44.970 回答