Codeigniter |在控制器中重复代码

时间:2016-11-18 21:34:38

标签: php codeigniter

我正在使用Codeigniter,问题是我的控制器中有很多重复的特定代码,我需要将这些代码放在一个地方然后在控制器内调用它。

示例:

 public function A()
    {
        something 1
        something 2
        something 3
        something 4

        $data = bla bla bla;
    }

    public function B()
    {
        something 1
        something 2
        something 3
        something 4

        for ($i=0; $i < ; $i++) { 
            # code...
        }
    }
    public function C()
    {
        something 1
        something 2
        something 3
        something 4

        if (condition) {
            # code...
        } else {
            # code...
        }

    }

每次我需要的东西(1             东西2             东西3             东西4) 我怎么能停止重复呢?

编辑: 这是我的“东西”代码:

$all_menus = $this->menu_model->get_all($this->getLanguage());
        foreach ($all_menus as $row) {
                $children = $this->menu_model->get_children($row->id_menu,$this->getLanguage());
                $row->children = $children;
                $data[] = $row;

2 个答案:

答案 0 :(得分:0)

您可以这样做:

class Something{

  public function A(){
   self::myFunction();
  }

  public function B(){
   self::myFunction();
  }

  private function myFunction(){
      $all_menus = $this->menu_model->get_all($this->getLanguage());
      foreach ($all_menus as $row) {
         $children = $this->menu_model->get_children($row>id_menu,$this->getLanguage());
         $row->children = $children;
         $data[] = $row;
      }
   }

}

通过这种方式,您可以访问使用self

调用myFunction的每个函数中的数据

答案 1 :(得分:0)

模特:

"authentication": {
     "type": "Basic",
     "username": "[list(resourceId('Microsoft.Web/sites/config', variables('webSiteName'), 'publishingcredentials'), '2016-08-01').properties.publishingUserName]",
     "password": "[list(resourceId('Microsoft.Web/sites/config', variables('webSiteName'), 'publishingcredentials'), '2016-08-01').properties.publishingPassword]"
}

任何控制者:

    class Something extends CI_Model
    {

        function __construct()
        {

            parent::__construct();
        }

        public function returnCommon()
        {
            $common = array('hello'=>'world','codeigniter'=>'awesome','chocolate'=>'yes please');

            return $common; 

        }


    }