CodeIgniter Forums
How to call a library function from within a model? - 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: How to call a library function from within a model? (/showthread.php?tid=39435)



How to call a library function from within a model? - El Forum - 03-10-2011

[eluser]carvingCode[/eluser]
I have a little utility function for turning a title into a uri_title. I need to use this in my db model, but calling it from my functions library doesn't work (I did add the library load statement, etc. in the db model). I added it to the constructor of the db model and it works fine.

Would appreciate a clarification on what to do to call a library function from within a model.

BTW: here's the uri_title function as a small bribe. Wink

Code:
function make_uri_title($name) {
    $items = Array('/\ /', '/\-/');
    return preg_replace($items, '_', strtolower($name));
}

edit: Re-reading docs on libraries, looks like they can only be used from within controllers. I guess I could use a 'require' statement...? Kinda feels un-OOP-y though.

TIA

Randy


How to call a library function from within a model? - El Forum - 03-10-2011

[eluser]bubbafoley[/eluser]
You can call libraries from models like you would in a controller.

Code:
class Test_model extends CI_Model {

  function foo
  {
    $this->load->library('bar');
    $this->bar->baz();
  }

}

as for the uri_title function, check out the url_helper.

http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html


How to call a library function from within a model? - El Forum - 03-10-2011

[eluser]carvingCode[/eluser]
Thanks, bubbafoley, on both accounts.

Retested my function call from model and it worked. Also, glad to know there's (another) built-in function in CI.

TA


How to call a library function from within a model? - El Forum - 03-10-2011

[eluser]InsiteFX[/eluser]
Why not just create a helper for it? Say utility_helper.php
Then all you need to do is load the helper not a complete library.
Code:
if ( ! function_exists('make_uri_title'))
{
    function make_uri_title($name)
    {
        $items = array('/\ /', '/\-/');
        return preg_replace($items, '_', strtolower($name));
    }
}

Not only that now you can add other functions to your helper as needed.

If you need to get to CI you can do this in a helper function:
Code:
// get the CI Superobject.
$CI =& get_instance();

InsiteFX