eoin
eoin

Reputation: 113

my project setup in codeigniter, need some tips on how to progress design-wise

for the most part i think my code is messy right now possibly because iam not really used to CI. I currently have one controller called 'user' which i will show below. in this controller I have methods such as login,logout etc. standard enough stuff in here like creating a session when the user logs in and destroying it when a user logs out. iam also tracking time as the system mimics a 'check in' system to get a users hours worked. the next part of the project requires access to the 'clients' tablem in the database that a user works with and is going to display some info about this client when a button is pressed, the clients themselves do not use this system but information about them needs to be viewed. Iam just wondering should i continue to add to my current controller and model or setup seperate classes next,seems to me the controller is already relatively big? here is my controller code.

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

class User extends CI_Controller {

    var $loggedin = FALSE;
    var $cdata;

    function __construct()
    {
         parent::__construct();
         $this->load->model("dbaccess");

        $this->cdata =array( "warning" => "","email"=> "","password"=> "","logintime"=>"","start"=>"","end"=>""
            ,"diff"=>"","totalhours"=>"","dis"=>$this); 

    }


public function index()
{
    if($this->session->userdata('email'))
    {
         $this->load->view('carerview',$this->cdata);
    }
    else
    {
        $this->load->view('mainview',$this->cdata);
    }

}


public function login()
{
        //get posted data. check if what is posted is in db.
        // if it is set loggedin=true + redirect to carer page + save data in session.        //get posted data. check if what is posted is in db.

        if(isset($_POST['email'])  )
            {$this->cdata['email'] = $_POST['email'] ;}
            else
            {$this->cdata['email'] ="";}
        if(isset($_POST['password']))
            {$this->cdata['password'] = $_POST['password'];}
            else
            {$this->cdata['password'] ="";}


        if($this->session->userdata('email'))
            {       
                $this->loggedin = true;
            }
        else
            {
                $this->loggedin = $this->dbaccess->check_input($this->cdata['email'],$this->cdata['password']);
            }




    if($this->loggedin === TRUE && !$this->session->userdata('email'))
        {

            $this->start_session();

            if(!$this->dbaccess->get_date_entry($this->session->userdata('email'),date("Y-m-d")))
            {
                $data =     array("email"=>$this->session->userdata('email'),"date"=>date("Y-m-d"),
                "hours"=>"0","starttime"=>date("Y-m-d     H:i:s",$this->session->userdata('last_activity')));
                $this->dbaccess->insert_daily_row($data);
            }

            $this->load->view('carerview',$this->cdata);
        }

    else if ($this->loggedin === TRUE && $this->session->userdata('email'))
        {
            $this->cdata['totalhours']= $this->session->userdata('totalhours');
            $this->cdata['logintime']= $this->session->userdata('last_activity');
            $this->load->view('carerview',$this->cdata);

        }

    else
        {
            $this->session->unset_userdata('last_activity');
            $this->cdata['warning']="Check failed ! Please try again";
            $this->load->view('mainview',$this->cdata);
        }
}


private function start_session()
{

    $this->load->library('session');
    $this->session->set_userdata('email',$this->cdata['email']);
    $this->cdata['totalhours']= $this->dbaccess->get_hours_by_date
    ($this->session->userdata('email'),date("Y-m-d",$this->session->userdata('last_activity')));
    $this->session->set_userdata('totalhours',$this->cdata['totalhours']);
}






private function calculatedifference($starttime,$endtime) // delete checkin time from checkouttime
{

    $diff=  abs(strtotime($starttime) - strtotime($endtime));
    $this->cdata['diff'] = date("H:i:s",$diff);
    $this->cdata['start'] = date("Y-m-d H:i:s", strtotime( $starttime)+(1 * 3600));
    $this->cdata['end']= date("Y-m-d H:i:s", strtotime($endtime) +(1 * 3600));
    return  date("H:i:s",$diff);

}


public function isLoggedIn()
{
    return $this->loggedin;
}



public function logOut()
{
    // update total hours and update checkout time.

    if($this->session->userdata('email')){
    $hours=$this->calculatedifference(date("Y-m-d H:i:s",$this->session->userdata('last_activity')),date("Y-m-d H:i:s"));
    $data =array("endtime"=>date("Y-m-d H:i:s"),"hours"=>$hours,"email"=>$this->session->userdata('email'),"date"=>date("Y-m-d"));
    $this->dbaccess->update_daily_row($data);}

        $this->load->view('mainview',$this->cdata);
        $this->session->sess_destroy();
}


public function admin()
{
    $this->load->view('adminpage',$this->cdata);
}







}

Upvotes: 0

Views: 432

Answers (2)

mixix
mixix

Reputation: 92

Heed the advise of the previous answer and also here's a little neat trick for when you deal with user specific content and public content. I have this controller called user_base.php, which is always loaded first when dealing with user specific content like data for logged in users:

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

class User_base extends CI_Controller
{
//define for later use in the construct
public $user_id;
public $username;

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

    // here load everything you will need to service users.
    $this->load->helper('url');
    $this->load->library('my_functions');
    $this->load->model('my_model');
    $this->lang->load('app');

    if($this->my_functions->is_logged_in() ){
        // if user is really logged in, I prepare often needed variables            
        $this->user_id = $this->my_functions->get_user_id();
        $this->username = $this->my_functions->get_username();

        // here i define global variables that once loaded are usable by every view file
        $gv['logged'] = true;
        $gv['username'] = $this->username;
        $gv['user_id'] = $this->user_id;
        $gv['something'] = $this->my_model->some_function($this->user_id);

        $this->load->vars($gv); 
    }
    else{ // if user is not logged in, throw him out.
        redirect('');
    }


   }
  }
  ?>

Now, with this base prepared I can start creating controllers for users like Accounts for user settings, view profiles and such. Notice that first you always load the base file first and then EXTEND your controllers with that base.

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

 require 'user_base.php';

 class Accounts extends User_base{

private $var;

function __construct()
{
    parent::__construct();      
    $this->var = 'some value';
}

function index(){
       $data['value_from_DB'] = $this->my_model->get_stuff($this->user_id, $this->var);
       $this->load->view('viewAccount', $data);
}

Notice also that now I can load user id from the user_base easily across all functions as well as the locally defined private variables.

And finally in the view file you can now call $username, because it was gloablly loaded in the user_base.php:

<p>Hello there, <?php echo $username?></p>

I would then do the same with public_base and admin_base, etc. In other words. I would define bases for the broadest categories I can imagine which are mutually exclusive, then create controllers around them that are lesser categories, like accounts for all functions managing user accounts (or "User" in your case), then Orders, for all views and reports and processes dealing with orders, or blog for blog part of the site, etc, etc.

Hope this helps with structuring and keeping code clean.

Upvotes: 0

geomagas
geomagas

Reputation: 3280

Well, using an MVC framework to end up with a one-controller application sounds like an overkill. That is, if it turns out your application needs only one controller implemented.

Moreover, you will most likely need functionality that doesn't fall under the "user" scope. Public content being a good (and obvious) example.

Besides, CI maps urls in a /controller/method/param0/param1/... nature, so keeping only User would make your entire url namespace hang below a /user/ path, and I don't think that's what you want.

So I'd go the multiple-controller way -- or rather, i'd use an MVC framework if my design implied such a demand.

Concerning your second question, there's no such thing as a big or small class (controller in your case). It depends on (1) how you model your application and (2) your coding habits.

Upvotes: 1

Related Questions