CodeIgniter Forums
Question about calling a library from within a library - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Question about calling a library from within a library (/showthread.php?tid=34478)



Question about calling a library from within a library - El Forum - 09-30-2010

[eluser]neomech[/eluser]
I have extended the standard form_validation library to add a username check for Ion Auth. The following code works, but I'm wondering if I'm doing it right. In particular, I would have thought that I should be calling the ion_auth library from within the constructor, but doing that I was never able to get the line in the user_check function to recognize ion_auth. I'm not a PHP or CI guru by any means, but something about what I've done seems "wrong" to me....

Any comments on my approach here would be greatly appreciated! Smile
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {
      
    function My_Form_Validation()
    {
        parent::CI_Form_Validation();
    }
    
    function username_check($username)
    {
        $CI =& get_instance();
        $CI->load->library('ion_auth');
        return ($CI->ion_auth->username_check($username) ? FALSE : TRUE);
    }
}



Question about calling a library from within a library - El Forum - 09-30-2010

[eluser]Jelmer[/eluser]
Alternative:
Code:
class MY_Form_validation extends CI_Form_validation {

    var $ion_auth;
      
    function My_Form_Validation()
    {
        parent::CI_Form_Validation();

        $CI =& get_instance();
        $CI->load->library('ion_auth');
        $this->ion_auth = $CI->ion_auth;
    }
    
    function username_check($username)
    {
        return ($this->ion_auth->username_check($username) ? FALSE : TRUE);
    }
}

Second alternative (changes only this method from your code):
Code:
function username_check($username)
    {
        get_instance()->load->library('ion_auth');
        return (get_instance()->ion_auth->username_check($username) ? FALSE : TRUE);
    }

Bottom line: nothing is "wrong", my preference used to be to use the first alternative. Nowadays I use either the second example or use a helper I wrote that allows usage like Ci::lib('ion_auth') and autoload if the lib wasn't loaded yet (AugmentedCI helper).


Question about calling a library from within a library - El Forum - 09-30-2010

[eluser]neomech[/eluser]
Thank you soooo much! Smile

Works perfectly, looks much cleaner, and I can add my email check without any code duplication now. Thanks again!