dongshuo5101 2013-10-08 17:19
浏览 14
已采纳

我在codeigniter中的项目设置,需要一些关于如何在设计方面取得进展的技巧

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);
}







}
  • 写回答

2条回答 默认 最新

  • doubu4826 2013-10-08 23:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题