thinkphp框架学习笔记(1)

利用假期简单学习一下tp框架。

  • 入口文件

tp5中自带入口文件,位于public/index.php中,文件内容包括

<?php

// [ 应用入口文件 ]

// 定义应用目录
define('APP_PATH', __DIR__ . '/../application/');
// 加载框架引导文件
require __DIR__ . '/../thinkphp/start.php';
?>

这段代码的作用是定义一个入口地址,例如localhost/tp5/public

  • 控制器

每一个模块都有属于自己的控制器,例如index中控制器位于application文件中的Index.php

在代码中我们可以做如下修改

<?php

namespace app\index\controller;

class Index
{
    public function index($name = 'World')
    {
        return 'Hello,' . $name . '!';
    }

在访问url时例如localhost.tp5.com?name=....

name参数即输入的参数可控

控制器其中一个作用在于访问任何子文件时都需要先进入其中的控制器中

  • URL和路由

url访问采用统一入口 url/index.php/模块/控制器/操作

例如我们输入www.tp5.com 首先默认进入的网址即www.tp5.com/index.php

如果需要控制入口地址 即需要访问控制器 在index.php中插入

<?php
namespace app\index\controller;

class Index
{
    public function index()
    {
        return 'index';
    }
    public function hello($name='')
    {
        return 'love,' .$name. '!';
    }
}

在url中输入url/index.php/index/index/hello/name/hsy

输出:love hsy

因此如果想访问index模块下的子程序 首先需要进入所属的控制器。

.htaccess

这个配置文件主要用来重写根目录,当用户访问网站时,这个配置文件可以将用户代入需要跳转的页面。

  • 定义路由

按如上规则定义文件位置时,需要先进入他的控制器,在进入指定文件。

如果一个功能非常复杂的网站,每一个控制器下包含的文件会更多,因此定义路由可以简化其中的过程。

return [
    // 添加路由规则 路由到 index控制器的hello操作方法
    'hello/:name' => 'index/index/hello',
];

该路由规则表示所有hello开头的并且带参数的访问都会路由到index控制器的hello操作方法。

此前url访问地址为index.php/index/index/hello/name/world

现在可以直接简化为index.php/hello/world

路由参数:return [ // 定义路由的请求类型和后缀 'hello/[:name]' => ['index/hello', ['method' => 'get', 'ext' => 'html']], ];

这里限制了请求方法为get并且只能以.html为结尾的文件。

路由变量

<?php
namespace app\index\controller;

class Blog
{
    public function get($id)
    {
        return 'cheak id='.$id;
    }
    public function read($name)
    {
        return 'check name='.$name;
    }
    public function archieve($year,$month)
    {
        return 'check'.$year.'/' .$month;
    }
}

在一个控制器内添加查找项目

在application 下面的route.php中添加

return [
    'blog/:year/:month' => ['blog/archive', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']],
    'blog/:id'          => ['blog/get', ['method' => 'get'], ['id' => '\d+']],
    'blog/:name'        => ['blog/read', ['method' => 'get'], ['name' => '\w+']],
];

访问url/blog/5 查找id=5

猜你喜欢

转载自www.cnblogs.com/sylover/p/11267449.html
今日推荐