Welcome Guest, Not a member yet? Register   Sign In
Access database active records from a custom library
#1

[eluser]polaris1927[/eluser]
I have defined a custom library function in

Code:
application/library/validate.php

This class needs to have access to a database, using

Code:
$this->db->get('business_names', $data);


Below is a code snippet from my validate.php class:

Code:
function contact($contact)
{
    if( trim( strlen($contact) ) > 0 && str_word_count($contact) > 0)
    {
        //does this contact exist in database
        $action = $this->db->get('business_names', array('name' => $contact));
        if( $action->num_rows() == 0 )
        {
            return TRUE;
        }
    }
    
    return FALSE;
}


BUT, I get the following error message:


A PHP Error was encountered
Severity: Notice

Message: Undefined property: Validate::$db

Filename: libraries/validate.php

Line Number: 54



Can annyone suggest a workaround?

Thanks.
#2

[eluser]polaris1927[/eluser]
I extended my validate library class as a Controller as follows:

Code:
class Validate extends Controller{

... and this got it working; but somehow I don't believe that this is the correct way to do things as validate is not a really a controller class.....
#3

[eluser]Seppo[/eluser]
You can get_instance
Code:
// Instead of
$action = $this->db->get('business_names', array('name' => $contact));
// you should use
$CI =& get_instance();
$action = $CI->db->get('business_names', array('name' => $contact));

Or use a model instead of a library
#4

[eluser]tschunde[/eluser]
Thx for info... Today I had the same problem. So I used an extra model... But I think that using a library that uses its own model is a bit too bloated for an acl. Now i put everything (including database related things) into the library. :cheese:
Just one hint from my side:
If you do not want to call $this->CI =& get_instance(); in every function of your library, just create a global variable called $CI and make that "$this->CI =& get_instance();" call in the constructor.

Examlpe:
Code:
class yourlibrary {
    
public $CI;

function acl() //Constructor
{
    $this->CI =& get_instance();
}

function dosomething()
{
       $this->CI->db->YOURACTIVERECORDCODE_INSERT_HERE;
}

}
#5

[eluser]Unknown[/eluser]
Thanks tschunde, thats exactly what i was looking for

Regards




Theme © iAndrew 2016 - Forum software by © MyBB