【问题标题】:create custom library with extends CI 3 core创建具有扩展 CI 3 核心的自定义库
【发布时间】:2016-05-13 06:06:31
【问题描述】:

我有一个自定义库来检查 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));
    }

  }
  ?>

怎么了?

这是显示的错误消息:

【问题讨论】:

  • 在你的控制器__construct方法中添加$this-&gt;load-&gt;library('basic');
  • 感谢 4 您的评论,iam 在自动加载配置中加载库。

标签: php function codeigniter class


【解决方案1】:

您需要在库中加载 CI 对象以访问它的对象:-

$CI = & get_instance();

在此之后,您可以在您的库中使用 CI 类,例如:-

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

【讨论】:

    【解决方案2】:

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

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

    基础类{

        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');
            }
        }
    

    }

    ?>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-17
      • 2014-12-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多