Php – CI Instance in Custom Library for CodeIgniter

codeigniterPHP

I am trying to create a custom User library in CodeIgniter. Inside this library I would like to use other CodeIgniter libraries and helpers but I am running into erros. Here are the steps I have taken:

  1. I created the User class in a User.php file and uploaded it to applications/libraries/.

  2. Inside application/config/autoload.php I am autoloading the User library.

Here is the code in my User library:

<?php 

    class User {

    private $CI;

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

        public function create_login_form()
        {
            echo 'hello';
            echo $this->CI->form->form_open();
        }

    }

/* End of file User.php */

Then in one of my views I am using to call the create_login_form method:

$this->user->create_login_form()

It seems like the method is being called because the hello is being echoed but when it gets to using the form helper form_open method I am getting the following error:

A PHP Error was encountered Severity: Notice Message: Undefined
property: Home::$form Filename: libraries/User.php Line Number: 46

Fatal error: Call to a member function form_open() on a non-object in
…/application/libraries/User.php on line 46

Any ideas what I am doing wrong?

Thanks!

Best Answer

class User {

    public function __construct()
    {
        $CI =& get_instance();
        $CI->load->helper('form');
    }

    public function create_login_form()
    {
        echo 'Title';
        echo form_open(); // Form open is helper. Not library
        echo 'Write something';
        echo form_close(); // Produces a closing </form> tag.
    }

}
Related Topic