[英]Codeigniter 3: how can I avoid repeating this chunk of code in my controllers?
I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4. 我正在使用 Codeigniter 3.1.8和Bootstrap 4中的基本博客应用程序 。
Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages. 所有控制器中都存在多个实体(Login.php和Register.php除外):静态数据,类别和页面。
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
Further more, in most controller, the code above appears more then one time. 此外,在大多数控制器中,上面的代码看起来多一次。
I am afraid this is mot the only case of repetitive code in the application. 我担心这是应用程序中重复代码的唯一情况。 (See the entire application, at its current state, on my Github account ).
( 在我的Github帐户中查看整个应用程序,当前状态)。
I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient. 我正在寻找经验丰富的PHP开发人员提供的具体和/或一般性建议,这些建议可以帮助我减少代码冗余并提高效率。
What is the best way to avoid the repeating of the code above in my controllers? 避免在控制器中重复上述代码的最佳方法是什么?
In CodeIgniter You can create a core controller in the following path: 在CodeIgniter中您可以在以下路径中创建核心控制器:
application/core/MY_Controller.php
Then you can use it to extend your controllers for example: 然后,您可以使用它来扩展控制器,例如:
class MY_Controller extends CI_Controller {
public function __construct() {
// your logic here
}
}
class Pages extends MY_Controller {
public function index() {
// display all pages here
}
}
You don't have to create the constructor in every class you make unless you need or override something, And if you want to have global data just create a protected property in your core controller & use it in other classes 您不必在每个类中创建构造函数,除非您需要或覆盖某些东西,如果您想拥有全局数据,只需在核心控制器中创建受保护的属性并在其他类中使用它
eg: 例如:
// MY_Controller
protected $data;
public function __construct() {
$this->data = $this->somemodel->get_static()
}
in your controllers you can do something like this 在你的控制器中你可以做这样的事情
public function index() {
$this->data['pages'] = $this->pagesmodel->get_pages();
$this->load->view('path/to/view', $this->data);
}
The core controller is automatically loaded if exists, just create the file & start using it. 核心控制器会自动加载(如果存在),只需创建文件并开始使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.