使用扩展CI 3核心创建自定义库

时间:2016-05-13 06:06:31

标签: php function codeigniter class

我有一个自定义库来检查AJAX请求,但它无效。

以下代码是我的自定义库:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Basic {

    // We'll use a constructor, as you can't directly call a function
    // from a property definition.
    public function __construct()
    {
            // Assign the CodeIgniter super-object
           // $this->CI =& get_instance()
    }


    public function check_ajax(){
        if (!$this->input->is_ajax_request()) {
           exit('No direct script access allowed');
        }
    }
}


?>

这是我的控制者:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Home extends CI_Controller {

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

    }

    function index(){
      $this->load->view('Vhome');
    }

    function article_list(){
        $this->basic->check_ajax();
        $res= array('status' => false,'noty'=>'Article is empty','res'=>array());
        $this->load->model('mquery');
        $articles=$this->mquery->read('articles','','','post_date DESC');
        if(!empty($articles)){
            $i=0;
            foreach ($articles as $key => $value) {
                $res['res'][$i]=$value->post_title;
                $i++;
            }
            $res['status']=true;
        }else{

        }

        die(json_encode($res));
    }

  }
  ?>

出了什么问题?

这是显示的错误消息: library ci error

2 个答案:

答案 0 :(得分:3)

您需要在库中加载CI对象以使用以下方式访问对象: -

$CI = & get_instance();

在此之后,您可以像在库中一样使用CI类: -

    public function check_ajax(){
            $CI = & get_instance();
            if (!$CI->input->is_ajax_request()) {
               exit('No direct script access allowed');
            }
        }

答案 1 :(得分:1)

感谢Manmohan,我更新了我的自定义库:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Basic {

    protected $CI;
    // We'll use a constructor, as you can't directly call a function
    // from a property definition.
    public function __construct()
    {
            // Assign the CodeIgniter super-object
           // $this->CI =& get_instance()
        $this->CI =& get_instance();
    }


    public function check_ajax(){
        if (!$this->CI->input->is_ajax_request()) {
           exit('No direct script access allowed');
        }
    }

}

&GT;