Welcome Guest, Not a member yet? Register   Sign In
[solved] I can't seem to make my library work
#1

[eluser]Saoshyant[/eluser]
Hi, very much new to CI and MVC in general. I'm building a simple website to learn the framework, but even after going through the tutorial twice, I seem to have hit a wall.

I have a complex menu present in every page, which is built using categories and subcategories, so, if I understand correctly, I should create a library to do this and load it in every controller that needs it.

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

class Menus {
  function alist() {
   $CI =& get_instance();
   $query = $CI->db->query('QUERY');
   return $query->row_array();
  }
}
?>

Then load it in one of the controllers:

Code:
$this->load->library('Menus');
  $testing = $this->menus->alist();
  print_r($testing);

I don't know if this is the right way of doing it. Worse, I can't seem to use db->query() even though I'm in theory following the steps in the user guide. Help?
#2

[eluser]InsiteFX[/eluser]
Did you save your library to ./application/libaries ?
Did you load the Database ?
#3

[eluser]Saoshyant[/eluser]
[quote author="InsiteFX" date="1329483377"]Did you save your library to ./application/libaries ?
[/quote]

Yes.

[quote author="InsiteFX" date="1329483377"]
Did you load the Database ?
[/quote]

Where specifically? I may have not.
#4

[eluser]Saoshyant[/eluser]
Ah. Changing it to the following fixes the issue, by invoking the CI instances that in turn get the database functions on.

Code:
class Menus {
public function __construct()
{
  $CI =& get_instance();
  $CI->load->database();
}

function alist() {
  $CI =& get_instance();
  $query = $CI->db->query('SELECT * FROM news');
  return $query->row_array();
}
}

HOWEVER, I'm wondering if I have to do the get_instance() bit in every single function. Seems like a lot of redundancy.
#5

[eluser]InsiteFX[/eluser]
You can either load it in your Controller:
Code:
$this->load->database();

Or you can Autoload it in ./application/config/autoload.php
Code:
$autoload['libraries'] = array(
'database',
'session'
);

It's also a good idea to autoload the URL Helper
Code:
$autoload['helper'] = array(
'url'
);
#6

[eluser]Saoshyant[/eluser]
I see. Thanks!
#7

[eluser]Aken[/eluser]
You can also keep yourself from repeating code.
Code:
class Menus {

protected $CI;

public function __construct()
{
  $this->CI =& get_instance();
  $this->CI->load->database();
}

public function alist()
{
  $query = $this->CI->db->query('SELECT * FROM news');
  return $query->row_array();
}

}
#8

[eluser]CroNiX[/eluser]
@aken forgot the db there in the query
#9

[eluser]Aken[/eluser]
Ah, yes good catch. Fixed that.




Theme © iAndrew 2016 - Forum software by © MyBB