Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom classes in CodeIgniter

Seems like this is a very common problem for beginners with CodeIgniter, but none of the solutions I've found so far seems very relevant to my problem. Like the topic says I'm trying to include a custom class in CodeIgniter.

I'm trying to create several objects of the class below and place them in an array, thus I need the class to be available to the model.

I've tried using the load (library->load('myclass') functions within CodeIgniter which sort of works, except it tries to create an object of the class outside the model first. This is obviously a problem since the constructor expects several parameters.

The solutions I've found so far is

  1. A simple php include which seems fine enough, but since I'm new to CodeIgniter I want to make sure I'm sticking to it as much as possible.
  2. Creating a "wrapper class" as suggested here, however I'm uncertain how I would implement this.

The class I want to include, User.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class User{
    public $ID = 0;
    public $username = 0;
    public $access_lvl = 0;
    public $staff_type = 0;
    public $name = 0;    

    public function __construct($ID, $username, $access_lvl, $staff_type, $name) 
    {
        $this->ID = $ID;
        $this->username = $username;
        $this->access_lvl = $access_lvl;
        $this->staff_type = $staff_type;
        $this->name = $name;
    }

    public function __toString() 
    {
        return $this->username;
    }
}
?>

Method (Model) which needs the User.php

function get_all_users()
{
    $query = $this->db->get('tt_login');
    $arr = array();

    foreach ($query->result_array() as $row)
    {
        $arr[] = new User
        (
            $row['login_ID'],
            $row['login_user'],
            $row['login_super'],
            $row['crew_type'],
            $row['login_name']
        );
    }    

    return $arr;
}

And finally the controller,

function index()
{
        $this->load->library('user');
        $this->load->model('admin/usersmodel', '', true);            

        // Page title
        $data['title'] = "Some title";
        // Heading
        $data['heading'] = "Some heading";
        // Data (users)
        $data['users'] = $this->usersmodel->get_all_users();
like image 686
Index Avatar asked Mar 01 '12 06:03

Index


People also ask

What is get_ instance() in php?

get_instance() is a function defined in the core files of CodeIgniter. You use it to get the singleton reference to the CodeIgniter super object when you are in a scope outside of the super object.

How to use get_ instance in CodeIgniter?

First, assign the CodeIgniter object to a variable: $CI =& get_instance(); Once you've assigned the object to a variable, you'll use that variable instead of $this : $CI =& get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url'); // etc.


2 Answers

If you have PHP version >= 5.3 you could take use of namespaces and autoloading features.

A simple autoloader library in the library folder.

<?php
class CustomAutoloader{

    public function __construct(){
        spl_autoload_register(array($this, 'loader'));
    }

    public function loader($className){
        if (substr($className, 0, 6) == 'models')
            require  APPPATH .  str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
    }

}
?>

The User object in the model dir. ( models/User.php )

<?php 
namespace models; // set namespace
if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class User{
 ...
}

And instead of new User... new models\User ( ... )

function get_all_users(){
    ....
    $arr[] = new models\User(
    $row['login_ID'],
    $row['login_user'],
    $row['login_super'],
    $row['crew_type'],
    $row['login_name']
    );
    ...
}

And in controller just make sure to call the customautoloader like this:

function index()
{
        $this->load->library('customautoloader');
        $this->load->model('admin/usersmodel', '', true);            

        // Page title
        $data['title'] = "Some title";
        // Heading
        $data['heading'] = "Some heading";
        // Data (users)
        $data['users'] = $this->usersmodel->get_all_users();
like image 111
Petter Kjelkenes Avatar answered Sep 20 '22 09:09

Petter Kjelkenes


CodeIgniter doesn't really support real Objects. All the libraries, models and such, are like Singletons.

There are 2 ways to go, without changing the CodeIgniter structure.

  1. Just include the file which contains the class, and generate it.

  2. Use the load->library or load_class() method, and just create new objects. The downside of this, is that it will always generate 1 extra object, that you just don't need. But eventually the load methods will also include the file.

Another possibility, which will require some extra work, is to make a User_Factory library. You can then just add the object on the bottom of the file, and create new instances of it from the factory.

I'm a big fan of the Factory pattern myself, but it's a decision you have to make yourself.

I hope this helped you, if you have any questions that are more related to the implementation, just let me/us know.

like image 41
Nico Kaag Avatar answered Sep 19 '22 09:09

Nico Kaag