2013-04-09 71 views
1

我试图获得来自数据库的网站的任何页面滚动的新闻,而无需传递变量在网站的每个控制器站点范围。所以我决定使用钩子而不是在每个控制器中传递滚动变量。笨-fetching数据与笨钩

我确实创造了这样的

class Scroll 
{ 

function getScroller() 
{ 

    $data = array(); 

    $CI =& get_instance(); 

    $CI->db->where('a_status','active'); 
    $CI->db->limit(4); 
    $CI->db->order_by('id','desc'); 

    $Q = $CI->db->get('news'); 
    if($Q->num_rows() > 0){ 
    foreach($Q->result_array() as $row){ 
     $data[] = $row; 
    } 
    } 
    $Q->free_result(); 
    return $data; 
} 



} 

一类我现在得到的是

Severity: Notice 

Message: Trying to get property of non-object 
Call to a member function get() on a non-object in E:\xampp\htdocs\ 

谁能帮我如何做到这一点?谢谢我想在任何控制器的视图中自动获取scrollernews,而无需传入每个控制器。谢谢

回答

0

如果你在视图层次上定义它,那就没有必要这样做。

您可以直接在视图中定义数据库请求。

其他方法将是具有分离的控制器,其与单独的视图,并将其装载在页面通过iframe中。它通常用于可以在以后加载到另一个页面的“Web小部件”。

0

扩展CI控制器的核心类应该会减少麻烦。 http://ellislab.com/codeigniter/user-guide/general/core_classes.html

应用/核心/ MY_Controller.php

class MY_Controller extends CI_Controller { 

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

     //By do this, all controllers who use this class as parent controller 
     //will have $news in their views 
     $this->load->vars(array( 
      'news' => array() 
     )); 
    } 
} 

应用/控制器/的welcome.php

class Welcome extends MY_Controller { 

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

应用/视图/ welcome_message.php

var_dump($news); 
0

使用分离的库或帮助程序并在控制器的结构上调用该方法,例如:

class My_Controller extends CI_Controller(){ 

    function __construct(){ 
     parent::__construct(); 
    //load your library 
    //call your library method 
    } 
    }