Mike DeMille
Mike DeMille

Reputation: 441

CodeIgniter Custom Library Not Loading

I'm new to CodeIgniter and trying to developing a fairly simple application with it -- just a form to process the registration for employees wanting a recreation center pass. I'm trying to separate things to make them cleaner.

Here is the code:

application/controllers/reccenter.php

class RecCenter extends CI_Controller {

    public function register() {
        $data['title'] = "Utah Valley Rec Center Registration";

        $this->output->enable_profiler(TRUE); // Put all the debug statements at the bottom of the page
        $this->load->helper('html');

        $this->load->library('form_validation');
        $this->form_validation->set_rules('userRecCenter', 'recreation center selection', 'required');

        $userRecCenter = $this->input->post('userRecCenter');
        $registerSelf = $this->input->post('registerSelf');
        $dependents = $this->input->post('dependents');

        if($this->input->post('registerSelf') && !$registerSelf) { // Employee not registering themselves
            $this->form_validation->set_rules('dependents', 'self selection or dependents', 'required');
        } else if($this->input->post('dependents') && count($dependents) == 1 && $dependents[0] == "") { // Employee only registering themselves
            $this->form_validation->set_rules('registerSelf', 'self selection or dependents', 'required');
        }

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('pages/reccenter/register', $data);
            $this->load->view('templates/footer', $data);
        } else {
            $this->load->library('Reccenterdao');
            $numRows = $this->reccenterdao->getRecCenterInfo();
            var_dump($numRows);

            // Check if already registered 
                // Redirect to different view to change their registration

            // Do the registration
                //redirect('reccenter/confirm');
        }
    }

    public function confirm() {
        $data['title'] = "Utah Valley Rec Center Registration Confirmation";

        $this->load->view('templates/header', $data);
        $this->load->view('pages/reccenter/confirm', $data);
        $this->load->view('templates/footer', $data);
    }
}

application/libraries/Reccenterdao.php

if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Reccenterdao {

    private $CI;

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

    private function connect() {
        $this->CI->load->database();
    }

    private function disconnect() {
        $this->CI->db->close();
    }

    public function getRecCenterInfo() {
        $this->connect();

        var_dump("Made it here");
        $result = $CI->db->query("SELECT * FROM ucfitness");
        var_dump($result->result());

        $this->disconnect();
        return $result->num_rows();
    }


}

Here are a couple of additional configuration items, so you know what all I've done to customize it a bit.

application/config/autoload.php

$autoload['helper'] = array('form', 'url');

webroot/index.php (For environment definitions)

if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == "my prod server") {
    define('ENVIRONMENT', 'prod');  
} else if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == "my stage server") {
    define('ENVIRONMENT', 'stage'); 
} else {
    define('ENVIRONMENT', 'test');  
}

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'test':
            error_reporting(E_ALL);
        break;

        case 'stage':
        case 'prod':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

I've also copied application/config/database.php into three folders, application/config/test/database.php, application/config/stage/database.php, and application/config/prod/database.php, to configure their individual connection parameters. Each environment has a different database server and credentials.

The problem is that when I submit the form and it makes it in to that else statement after the form validation $this->form_validation->run() I'm getting only a blank screen. None of my desperate var_dumps, nothing. So, after all of my attempts and different methods of getting this to work, a few questions have come up.

  1. What isn't working in the library? After going through all the tutorials/questions that I can find, it looks like I'm doing it right.
  2. How do I make it so that I can actually debug the code? I get no errors in the browser and no errors on the Apache error log. What else can I do?
  3. What would the best practice be for separating the DAO from the Controller? From what I could tell, making this a library like I'm trying would be the best idea. It is probably only going to be used by this one controller, which will handle both registration and modification of the registration. I will be writing a couple of other applications that will all sit within this CI instance, but they're going to be fairly separate and will not need to use the same DAO.
  4. Can I use CamelCase for the library file name as long as it starts with a capital letter? Reccenterdao.php is a lot less friendly than RecCenterDAO.php.

============================================================

EDIT: I changed the whole thing to a model, but I'm getting the same functionality - blank screen with no errors. It seems to load the model, because it dies when I try to actually use it with the line $numRows = $this->dao->getRecCenterInfo();

I know the whole thing is pointless right now because I haven't put functionality to use the database or parse the user input. That's the whole point. I was trying to get it to work before I went through the effort of putting in all my business logic.

application/models/rec_center_dao.php

class Rec_center_dao extends CI_Model {

    public function __construct() { 
        parent::__construct();
    }

    private function connect() {
        $this->load->database();
    }

    private function disconnect() {
        $this->db->close();
    }

    public function getRecCenterInfo() {
        $this->connect();

        var_dump("Made it here");
        $result = $this->db->query("SELECT * FROM ucfitness");
        var_dump($result->result());

        $this->disconnect();
        return $result->num_rows();
    }
}

Relevant section of application/controllers/reccenter.php

    if ($this->form_validation->run() == FALSE) {
        $this->load->view('templates/header', $data);
        $this->load->view('pages/reccenter/register', $data);
        $this->load->view('templates/footer', $data);
    } else {
        $this->load->model('Rec_center_dao', 'dao');
        $numRows = $this->dao->getRecCenterInfo(); // This is where it dies
        var_dump($numRows);

        // Check if already registered 
            // Redirect to different view to change their registration

        // Do the registration
            //redirect('reccenter/confirm');
    }

============================================================

EDIT2: Thanks to the comments, I've figured out that it's a problem connecting to the database. It errors out when I call $this->load->database();. I've confirmed that with the credentials I have I can manage the database with phpMyAdmin (I don't have shell access to test there).

application/config/test/database.php

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'my.hostname.com';
$db['default']['username'] = 'db_username';
$db['default']['password'] = 'db_password';
$db['default']['database'] = 'db'
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = TRUE;

With the above configurations in webroot/index.php and application/config/test/database.php it should pick up the settings for the different environments and take care of it accordingly, correct? But if I put a var_dump in either application/config/database.php or application/config/test/database.php it doesn't show up at all. I confirmed that the environment is being set correctly (at least while I'm working on test).

Upvotes: 4

Views: 4200

Answers (2)

Mike DeMille
Mike DeMille

Reputation: 441

Turns out the problem was my PHP installation. I'm running Windows 7 and used the MSI installer to install PHP 5.2.14. I used the php-5.2.14-Win32-VC6-x86.zip to redo the installation. Unzipped it, put it in place, reconfigured the php.ini, and it worked.

Don't use the MSI installers!

Upvotes: 0

Damien Pirsy
Damien Pirsy

Reputation: 25435

Surely, your class has these errors (the rest of the code looks fine):

private function connect() {
    $CI->load->database();
}

Should be:

private function connect() {
    $this->CI->load->database();
}

Since you've assigned $this->CI in the constructor, and you want to use that class property, not just a newly created $CI variable. Same goes for the disconnect() method, which should be:

private function disconnect() {
    $this->CI->db->close();
}

Then, here:

public function getRecCenterInfo() {
    connect();

    var_dump("Made it here");
    $result = $CI->db->query("SELECT * FROM ucfitness");
    var_dump($result->result());

    disconnect();
    return $result->num_rows();
}

You should have instead (errors highlighted in the comments):

public function getRecCenterInfo() {
    $this->connect(); // it's a method in the class, not a regular function
    $result = $this->CI->db->query("SELECT * FROM ucfitness"); // The property is $this->CI
    $this->disconnect(); // same as $this->connect();
    return $result->num_rows();
}

Aside from these errors, your class so far it's pretty useless, you would achieve the same using the DB class, maybe autoloaded, in a regular model.

Upvotes: 1

Related Questions