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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵