马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
在CodeIgniter中创建库(Library)是一个很好的方法来封装常用的功能,使其在差别的控制器或视图中重用。下面是如安在CodeIgniter中创建和利用库的步调:
1. 创建库文件
起首,在 application/libraries 目次下创建一个新的 PHP 文件。比方,你可以创建一个名为 MyLibrary.php 的文件。- application/
- ├── libraries/
- │ └── MyLibrary.php
复制代码 2. 编写库类
在 MyLibrary.php 文件中,编写你的库类。确保你的类扩展了 CI_Controller 或 CI_Base(取决于你的需求)。通常,我们会扩展 CI_Base,由于库通常不须要完备的控制器功能。- <?php
- defined('BASEPATH') OR exit('No direct script access allowed');
- class MyLibrary {
-
- protected $CI;
- // 构造函数,获取CI超级对象的实例
- public function __construct() {
- $this->CI =& get_instance();
- }
- // 示例方法
- public function say_hello($name) {
- return "Hello, " . $name . "!";
- }
- // 另一个示例方法,可以使用CodeIgniter的资源
- public function get_data_from_db($table, $where = array()) {
- $this->CI->load->database();
- $query = $this->CI->db->get_where($table, $where);
- return $query->result_array();
- }
- }
复制代码 3. 在控制器中加载和利用库
在你的控制器中,你可以通过 $this->load->library 方法来加载这个库,并利用它的方法。- <?php
- defined('BASEPATH') OR exit('No direct script access allowed');
- class Welcome extends CI_Controller {
- public function index() {
- // 加载库
- $this->load->library('MyLibrary');
- // 使用库的方法
- $hello_message = $this->mylibrary->say_hello('World');
- echo $hello_message; // 输出: Hello, World!
- // 从数据库中获取数据
- $data = $this->mylibrary->get_data_from_db('your_table_name', array('id' => 1));
- print_r($data);
- }
- }
复制代码 4. 自动加载库(可选)
如果你渴望在一个或多个控制器中频仍利用某个库,可以在 application/config/autoload.php 文件中自动加载它。- $autoload['libraries'] = array('database', 'session', 'MyLibrary');
复制代码 留意事项
- 定名规范:库的类名和文件名应该利用大驼峰定名法(PascalCase)。比方,类名 MyLibrary 对应的文件名应为 MyLibrary.php。
- 安全性:确保你的库代码是安全的,克制直接袒露于外部哀求。
- 文档:为你的库添加文档解释,以便其他开辟者明白其用途和用法。
通过这些步调,你可以在CodeIgniter中创建和利用自界说库,从而构造代码并进步代码的重用性。
|