douxu2081 2014-08-16 17:07
浏览 23
已采纳

CodeIgniter控制器/视图困境

I have created a simple register/login system and it (I think) works well so far.

Now I want to implement some of it's functions to my site.

controllers/main.php:

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

class Main extends CI_Controller
{
    public function index()
    {
        $this->home();
    }

    public function home()
    {
        $this->load->view('home.php');
    }
}

views/home.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Home</title>
</head>
<body>

<div id="container">
    <?php if ($this->session->userdata('is_logged_in')): ?>

        logged in as: <?php echo $this->session->userdata('username'); ?></br>
        <a href="<?php echo base_url().'login/logout'; ?>">Logout</a>

    <?php else: ?>

        not logged in</br></br>

        <?php echo form_open('login'); ?>
        <?php echo form_error('username'); ?>
        <input type="text" name="username" placeholder="Login" />
        </br>
        <?php echo form_error('password'); ?>
        <input type="password" name="password" placeholder="Password" />
        </br></br>
        <div><input type="submit" value="Sign in" /></div>
        <?php echo form_error('login_validation'); ?>
        </form>

    <?php endif ?>
</div>

</body>
</html>

Is this the right way of doing things in CI?

  • 写回答

1条回答 默认 最新

  • duanou2016 2014-08-16 17:34
    关注

    For controller part instead of using the home(), you can directly load the view in index() because internally you are navigating from index to home() without any specific reason.

    Also the loading view doesn't require ".php" extension in your file and you can do like this:

    $this->load->view('home');
    

    Where home.php is the file located inside application/views/

    For showing the error messages, you can use another optimal way by defining the validation rules(in array fromat) inside config/form_validation.php and just require below code to show all messages instead one by one

    <?php echo validation_errors()?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
  • ¥15 应用商店如何检测在架应用内容是否违规?
  • ¥15 Ubuntu系统配置PX4
  • ¥50 nw.js调用activex
  • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的
  • ¥15 将安全信息用到以下对象时发生以下错误:c:dumpstack.log.tmp 另一个程序正在使用此文件,因此无法访问
  • ¥15 速度位置规划实现精确定位的问题
  • ¥15 MAC虚拟机(win11)USB插上后无串口com,无法烧录