Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,574
    Rep Power
    171

    Is this the right way of structuring MVC?


    Hello friends;

    I am new to CI and MVC. This is a very basic login system.

    I was wondering if I am doing ok or I am totally off track. Please comment or give me tips that I could improve my knowledge and turn them to skills and I become invincible. Thanks

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

    class 
    Log_in extends CI_Controller
        
    {
        public 
    $session_array;
        public function 
    index()
            {
                
    $data['title'] = "Log In Page";
                
    $this->load->vars($data);
                
    $this->form();
            }
        public function 
    form()
            {
                if(isset(
    $_POST['submit']))
                    {
                        if(
    $this->validate($this->input->post('email'), $this->input->post('password')))
                            {
                                
    redirect('/account''refresh');
                            }
                    }
                
    $this->view_things();
             }
         public function 
    validate($email=NULL)
             {
                 
    $this->form_validation->set_rules('password''Password''required');
                 
    $this->form_validation->set_rules('email''Email''required|valid_email|callback_validate_membership');
                 if (
    $this->form_validation->run())
                     {    
                         return 
    true;
                     }
                 else
                     {
                         return 
    false;
                     }
             }
         
         public function 
    validate_membership($email)
             { 
                 
    $password $this->input->post('password');
                 
    $this->load->model('login_model');
                 
    $result $this->login_model->valid_member($email$password);
                 if(
    $result)
                     {
                         
    $sess_array = array();
                         foreach(
    $result as $row)
                              {
                                 
    $sess_array = array('name'=>$row->name'email'=>$row->email'login'=>true);
                                 
    $this->session->set_userdata('logged_in'$sess_array);
                              }
                         return 
    true;
                     }
                 else
                     {
                         
    $this->form_validation->set_message('validate_membership''Invalid login details');
                         return 
    false;
                     }
             }
         public function 
    view_things()
            {
                
    $this->load->view('header_view');
                
    $this->load->view('log_in_view');
                
    $this->load->view('footer_view');
            }
    }
    Model
    PHP Code:
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class 
    Login_model extends CI_Model
        
    {
            function 
    valid_member($email$password)
                {
                    
    $sql "SELECT * FROM members WHERE email = ? AND password = ? ";
                    
    $query $this->db->query($sql, array($emailmd5($password)));
                    if(
    $query->num_rows()==1)
                        {
                            
    $results $query->result();
                            return 
    $results
                        }
                    else
                        {
                            return 
    false;
                        }    
                }
        }
    View
    PHP Code:
    <div id="common_div"><?php echo validation_errors();?>
    <form action ="<?php echo site_url();?>log_in" method="post">
        <table style="width:100%">
            <tr>
                <td style="width:100px">Email</td>
                <td><input class = "text-box" type="text" name="email" value="<?php echo set_value('email'); ?>" id="email" /></td>
            </tr>
            <tr>
                <td style="width:100px">Password</td>
                <td><input class = "text-box" type="password" name="password" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Log In" name="submit" class="input_submit"/></td>
            </tr>
        </table>
    </form>
    </div>
    Last edited by zxcvbnm; November 5th, 2012 at 06:04 PM.
  2. #2
  3. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,540
    Rep Power
    2337
    It's usually:

    Model returns data to the Controller
    Controller loads data into View
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    29
    Rep Power
    0
    I still dont understand being the php variable in the view layer.

    PHP Code:

    <div class="blah"><?php echo $var?></div>
    this is spaghetti code that you know...

    whereas:

    PHP Code:

    <div class="blah">{var}</div
    I think this kind is better...

    Slip up?
  6. #4
  7. Come play with me!
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,749
    Rep Power
    9397
    Originally Posted by maximas
    Slip up?
    No. You like views that have to run through some preprocessor (like Smarty) while zxcvbnm's view is a simple PHP script.
  8. #5
  9. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,692
    Rep Power
    6351
    PHP was originally designed to be a templating language. That's why it's so often mixed in with HTML/JS like in zxcvbnm's script.

    To take a templating language, and use it to build a templating language is overkill. Plus, you have to learn all the syntax again, and you lose access to all the really awesome PHP functions that work on strings, specifically HTML strings.

    My company uses twig. It took me literally 2 hours to figure out how to print raw HTML into a twig template. I already know the answer for PHP, but I couldn't get to it because twig was preventing me from using one of the most powerful web programming languages in the world.

    Some people disagree, and prefer twig or smarty because they were taught that "display" and "business" should be separate, and therefore have decided that the "separate" means "separate language entirely."
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    29
    Rep Power
    0
    requinix and maniacDan again hi..!

    I use the following code for template system:


    index.php:

    PHP Code:

    class index extends Controller 

    function 
    home()

    {

    //variables in the view layer
    $var=array(
                    
    "foo"
                   
    );


    //values loaded to view
    $val=array(
                    
    "blabla"
                   
    );


    echo 
    $this->view_load($var,$val,"view");

    }




    view.php:

    PHP Code:

    <div class="abc">{foo}</div

    I can see as "blabla" output on the screen when index file worked.


    well, how is the view_load method in the controller class.

    this like:

    PHP Code:

    function view_load ($pat,$rep,$data,$loop='')
            {
                 
                if(
    $loop=='')
                    {
                        if(
    preg_match('@(.*)@is',file_get_contents('applications/view/'.$this->template_dir.'/'.$data.'.php'),$param)) 
                            {
                                
    $data_file=$param[1];
                            }
                            
                    }
                    else {
                    
                        if(
    preg_match('@<loop id="'.$loop.'">(.*?)</loop>@is',file_get_contents('applications/view/'.$this->template_dir.'/'.$data.'.php'),$param)) 
                            {
                                
    $data_file=$param[1];
                            }
                            
                        }
                        
                                    
                
    $pat_ex=$pat;
                
    $pat_count=count($pat_ex)-1;
                
                
    $i="-1";
                foreach (
    $pat_ex as $pat 
                {
                    
    $i++;
                    
    $pattern[$i]='/{'.$pat.'}/';
                }
                
                
    $rep_ex=$rep;
                
    $rep_count=count($rep_ex)-1;
                
                
    $i=count($pat_ex);
                foreach (
    $rep_ex as $rep )
                 { 
                    
    $i--;
                    
    $replace[$i]=''.$rep.'';
                 }
                 
                 
                  return 
    preg_replace($pattern,$replace,$data_file);
                  
            } 

    in conclusion: the code snippet works with doing preg_replace.

    How accurate is this?
  12. #7
  13. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,574
    Rep Power
    171
    Originally Posted by ptr2void
    It's usually:

    Model returns data to the Controller
    Controller loads data into View
    Isn't it what my code is doing? I don't understand the point of your reply. Thank you.
  14. #8
  15. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,574
    Rep Power
    171
    Originally Posted by ManiacDan
    PHP was originally designed to be a templating language. That's why it's so often mixed in with HTML/JS like in zxcvbnm's script.

    To take a templating language, and use it to build a templating language is overkill. Plus, you have to learn all the syntax again, and you lose access to all the really awesome PHP functions that work on strings, specifically HTML strings.

    My company uses twig. It took me literally 2 hours to figure out how to print raw HTML into a twig template. I already know the answer for PHP, but I couldn't get to it because twig was preventing me from using one of the most powerful web programming languages in the world.

    Some people disagree, and prefer twig or smarty because they were taught that "display" and "business" should be separate, and therefore have decided that the "separate" means "separate language entirely."
    Hello; as you can see I am trying out Codeigniter. I still don't know if you are saying the way I am doing it is right or wrong. I thought there is gonna be alot of focus on model and controller, but view got all the attention! What I got from your response, I assume you don't like prefer it to using something like twing. My English is not the best. What would you change in the way I did it? Thanks
  16. #9
  17. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,574
    Rep Power
    171
    Originally Posted by maximas
    I still dont understand being the php variable in the view layer.

    PHP Code:

    <div class="blah"><?php echo $var?></div>
    this is spaghetti code that you know...

    whereas:

    PHP Code:

    <div class="blah">{var}</div
    I think this kind is better...

    Slip up?
    Hello. Have you heard of CodeIgniter and how to use views? Is that spaghetti as well or am I missing something you are saying.
  18. #10
  19. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,574
    Rep Power
    171
    Originally Posted by requinix
    No. You like views that have to run through some preprocessor (like Smarty) while zxcvbnm's view is a simple PHP script.
    Hello. So am I doing right or no? WHat would you change? Thanks.
  20. #11
  21. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,540
    Rep Power
    2337
    I don't know CI, but it sure looks to me like you might be loading your view variables in the Model with this:

    php Code:
    $this->load->vars($data);


    but again, not knowing CI, that could be SOP. The fact that the same call exists in your controller leads me to believe I'm correct, and that what you're doing in the model with this call is unnecessary.
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    29
    Rep Power
    0
    Originally Posted by zxcvbnm
    Hello. Have you heard of CodeIgniter and how to use views? Is that spaghetti as well or am I missing something you are saying.
    yes.codeigniter which I know,but I dont use it.Because,I have my own framework.Already it seems like Codeigniter.
    Codeigniter is a professional framework the worldwide.I accept it.but php is open source and concern to free developers.So,I want use on my own the php
  24. #13
  25. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,301
    Rep Power
    7170
    ptr2void's note regarding loading data directly into your view from your model is the only MVC-architecture issue that I see.


    Your model does have a SQL injection vulnerability though because you don't escape $email before using it in your query. $this->db->escape() serves the same purpose as mysql_real_escape_string, or you can use CI's built in database utility methods, which escape data also:
    PHP Code:
    $database_results $this->db->get_where('members', array('email' => $email)); 
    The utility methods are not meant to replace all SQL queries, but for simple selects, inserts, updates and deletes they are pretty convenient.

    Your view has an XSS vulnerability because you don't escape $email before outputting it; use htmlentities on it to prevent that.

    It would also be a good idea to make the helper methods in your controller (everything except index in this case) protected so that people can't execute those directly.


    Regarding ptr2void's note, it isn't uncommon to invert the return logic on your validation methods; ie: have false mean success and a true-ish value mean failure. This is because it is common for there to be multiple failure states, but only one success state. For example, I commonly return an array from validation methods; an empty array evaluates to false and means that no errors occurred, while an array with one or more elements means that one or more errors occurred.
    PHP Code:
    if($errors validate()) {
      
    // failure state
    } else {
      
    // success state

    Comments on this post

    • web_developer agrees : Either useActive Record Pattern OR use some ORM
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  26. #14
  27. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,574
    Rep Power
    171
    Originally Posted by ptr2void
    I don't know CI, but it sure looks to me like you might be loading your view variables in the Model with this:

    php Code:
    $this->load->vars($data);


    but again, not knowing CI, that could be SOP. The fact that the same call exists in your controller leads me to believe I'm correct, and that what you're doing in the model with this call is unnecessary.
    No you're right. I changed the code. Please check and let me know if it's right now. Thanks.
  28. #15
  29. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,574
    Rep Power
    171
    Originally Posted by maximas
    yes.codeigniter which I know,but I dont use it.Because,I have my own framework.Already it seems like Codeigniter.
    Codeigniter is a professional framework the worldwide.I accept it.but php is open source and concern to free developers.So,I want use on my own the php
    Isn't it like re-inventing the wheel? I am sure you have good reasons : )
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo