Is it OK to put conditional logic on CodeIgniter V

2019-02-22 10:51发布

问题:

So I am in a dilemma at the moment. I want to implement a Login button on my site, which appears when no user is logged in. However, I want the button to change to a link to the user's profile if someone is already logged in.

I don't know if the right way to do this is to put an if statement in the View, which renders different HTML based on the data passed from the Controller, or if the Controller needs to decide if a user is logged in or not, and pass the appropriate data structures to the View. Which is the proper way to do it in CodeIgniter?

回答1:

The controller is for calculating and manipulating data and passing the results to the view, and the view takes the results and render them to HTML.

If you should use if statement in the view to show or hide some markup, you are allowed!

but if the changing section contains a lot of information, I suggest using partial views and passing their content as a variable to the main view. And doing all these in controller.

To do that in CodeIgniter:

Controller:

class Foo extends CI_Controller {
    public function bar()
    {
        // prevent getting error.
        $data['partial'] = '';

        // check if user is logged in.
        if ($this->session->userdata('user_id') == TRUE) {
            $data['partial'] = $this->load->view('partial/baz', '', TRUE);
        } else {
            $data['partial'] = $this->load->view('partial/qux', '', TRUE);
        }

        $this->load->view('my_view', $data);
    }
}

Assumption: user_id is set in CI session when user log in.

View:

<?php echo $partial; ?>


回答2:

In Codeigniter,you can put if and else statement in view.

if($this->session->userdata('your_session_variable'))
{
    ?>
    <a href="profile_page_link">Profile</a>
    <?php
}
else
{
    ?>
    <a href="login_page_link">Login</a>
    <?php
}


回答3:

It's obviously possible to have logic embedded in a View, but the idea on a MVC is to have all the logic in the Controller, so I guess you'll be defeating the purpose of using Codeigniter. The views in general are used to render content passed on by the controller.



回答4:

This applied to any MVC based application, not just CI.

Since you're changing the way the view is displayed to the user, there is nothing wrong with putting a condition within your view. However, the logic to this should be carried out within your controller. For example, your controller could look something like:

class x
{
  public function index()
  {
    if($session->get('logged_in') === true){
      // send a variable to the view
    }
  }
}

then within your view,

<?php if(isset($logged_in)): ?>
Hey User! <a href="">logout</a>
<?php else: ?>
<a href="">login here</a>
<?php endif; ?>

Obviously this will get tiresome to do within each controllers method, so check out this question which will allow you to avoid having duplicate code.