Codeigniter 4基础教程(10)-- 注册登陆案例(0)

前言:本节将以Codeigniter 4.0.3为基础,讲解一个注册和登陆的案例
0.安装Wamp环境(略)
wamp使用得比较普遍,我使用的是PHP 7.3 的版本。安装步骤网上很多,略过。
1.安装配置CI4
下载ci4的源代码报,解压到wamp的www/ci4signup/文件夹中
拷贝app/public/的.htaccess和index.php到app/下,以此来去掉路径中的public。
修改app/index.php,去掉…/, 代码如下

$pathsPath = realpath(FCPATH . 'app/Config/Paths.php');

浏览器输入http://localhost/ci4signup/,结果如下:
在这里插入图片描述
修改app/Config/App.php

public $baseURL = 'http://localhost/ci4signup/';
public $indexPage = '';

小试身手,做个测试:
app/controllers/Home.php

<?php namespace App\Controllers;

class Home extends BaseController
{
    
    
	public function index()
	{
    
    
		return view('welcome_message');
	}
	public function method(){
    
    
		echo '没错,就是我';
	}
}

http://localhost/ci4signup/home/method, 结果如下

在这里插入图片描述
配置数据库
建立个数据库ci4signup, 修改配置
app/Config/database.php

<?php namespace Config;

/**
 * Database Configuration
 *
 * @package Config
 */

class Database extends \CodeIgniter\Database\Config
{
    
    
	/**
	 * The directory that holds the Migrations
	 * and Seeds directories.
	 *
	 * @var string
	 */
	public $filesPath = APPPATH . 'Database/';

	/**
	 * Lets you choose which connection group to
	 * use if no other is specified.
	 *
	 * @var string
	 */
	public $defaultGroup = 'default';

	/**
	 * The default database connection.
	 *
	 * @var array
	 */
	public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'ci4signup',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

	/**
	 * This database connection is used when
	 * running PHPUnit database tests.
	 *
	 * @var array
	 */
	public $tests = [
		'DSN'      => '',
		'hostname' => '127.0.0.1',
		'username' => '',
		'password' => '',
		'database' => ':memory:',
		'DBDriver' => 'SQLite3',
		'DBPrefix' => 'db_',  // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

	//--------------------------------------------------------------------

	public function __construct()
	{
    
    
		parent::__construct();

		// Ensure that we always set the database group to 'tests' if
		// we are currently running an automated test suite, so that
		// we don't overwrite live data on accident.
		if (ENVIRONMENT === 'testing')
		{
    
    
			$this->defaultGroup = 'tests';

			// Under Travis-CI, we can set an ENV var named 'DB_GROUP'
			// so that we can test against multiple databases.
			if ($group = getenv('DB'))
			{
    
    
				if (is_file(TESTPATH . 'travis/Database.php'))
				{
    
    
					require TESTPATH . 'travis/Database.php';

					if (! empty($dbconfig) && array_key_exists($group, $dbconfig))
					{
    
    
						$this->tests = $dbconfig[$group];
					}
				}
			}
		}
	}
}

2.session的角色
session是CI框架中至关重要的传递数据的媒介,这里小试身手做个演示,看看里面的内容是什么:

<?php namespace App\Controllers;

class Home extends BaseController
{
    
    
	public function index()
	{
    
    
		return view('welcome_message');
	}
	public function method(){
    
    

	}
	public function setsession(){
    
    
		$mysession = session();
		var_dump($mysession);
		echo '==============';
		$myarray = [
			'name'=>'yyys',
			'email'=>'yyyfadfs',
			'add'=>'yyysfadga'
		];
		$mysession->set('key',$myarray);
	}
	public function getsession(){
    
    
		$mysession = session();
		var_dump($mysession->get('key'));
	}
	public function destroysession(){
    
    
		$mysession = session();
		$mysession->destroy();
	}
}

以此输入http://localhost/ci4signup/home/setsession, 和
http://localhost/ci4signup/home/getsession, http://localhost/ci4signup/home/destroysession, http://localhost/ci4signup/home/getsession查看结果。

3.创建User控制器
app/controllers/User.php
注意,这里对路由进行配置如下
app/Config/Routes.php

/**
 * --------------------------------------------------------------------
 * Router Setup
 * --------------------------------------------------------------------
 */
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('user');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);

$routes->get('/', 'user::index');

app/Controllers/User.php

<?php namespace App\Controllers;

class User extends BaseController{
    
    

    public function index(){
    
    
        echo 'I am fine';
    }

    public function register(){
    
    
        // echo '注册开始';
        helper('form');
        return view('signup');
    }

    public function newuser(){
    
    
        $myvalues = $this->validate([
            'name'=>'required',
            'email'=>'required',
            'password'=>'required',
        ]);
        if(!$myvalues){
    
    //没有通过条件检验
            return $this->register();
        }else{
    
    //通过条件检验后,取值
            $myrequest = \Config\Services::request();
            echo $myrequest->getVar('name');
            echo $myrequest->getVar('email');
            echo $myrequest->getVar('password');
        }

    }
}

app/Views/signup.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register a New User</title>
</head>
<body>
    <?php
        echo \Config\Services::validation()->listErrors();

        echo form_open('user/newuser');
        echo 'Enter your name ', form_input('name','',''), '<br>';
        echo 'Enter your password ', form_input('password','',''), '<br>';
        echo 'Enter your email ', form_input('email','',''), '<br>';
        echo form_submit('','Create Now');

        echo form_close();
    ?>
    
</body>
</html>

http://localhost/ci4signup/user/register进行测试
至此,实现了一个简单的form条件验证以及取值。
后面的讲解从model开始。

猜你喜欢

转载自blog.csdn.net/yaoguoxing/article/details/107294307