Welcome Guest, Not a member yet? Register   Sign In
How to call a library function from within a model?
#1

[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
#2

[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-gui...elper.html
#3

[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
#4

[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




Theme © iAndrew 2016 - Forum software by © MyBB