Thinkphp
Allen 2022-10-20 00:38:06 3264 0 0 0 0
Thinkphp,Thinkphp笔记,TP6控制器定义,控制器路径修改,基础控制器、空控制器、多级控制器。控制器,即controller,控制器文件存放在controller目录下.如果想改变系统默认的控制器文件目录,可以在 config 下route.php 配置。

05,控制器的定义

一,控制器定义

1.控制器,即controller,控制器文件存放在controller目录下;

2.如果想改变系统默认的控制器文件目录,可以在 config 下route.php 配置:

// 访问控制器层名称

controller_layer=>controller123,

3.类名和文件名大小写保持一致,并采用驼峰式(首字母大写)﹔

namespace appcontroller;

class Test {...}

4.从上面两段代码得知Test.php 的实际位置为: appcontrollerTest.php

5.在Test类创建两个方法 index(默认)和 hello,访问URL如下:

namespace appcontroller;
class Test
{
	public function index()
	{
		return "test-->index ";
	}
	public function hello($name='')
	{
		return "hello ".$name;
	}
}

http://localhost:8000/test/ (index可以省略)

http://localhost:8000/test/hello

http://localhost:8000/test/hello/name/world

6.那么如果创建的是双字母组合,比如 class Hellgworld,访问URL如下:

namespace appcontroller;
class HelloWorld
{
	public function index(){
		return "hello world-->index";
	}
}

http://localhost:8000/helloworld

http://localhost:8000/hello_world

7.如果你想避免引入同类名时的冲突,可以route.php 设置控制器后缀:

有时控制器和模型经常起同样的名字,引用命名空间时注意一下也可以。

controller_suffix=> true,

(开启后,控制器命名必须后面带cotroller,模型后面必须带model,可以不开启)

此时,Test.php就必须改成Testcontroller.php,并类名也需要增加后缀;

...

二,渲染输出

1. ThinkPHP直接采用方法内return返回的方式直接就输出了;

2.数组默认不支持输入,可以使用json输出,直接采用json函数;

	public function arrayoutput(){
		$data = array('a'=>1,'b'=>2,'c'=>3);
		return json($data);
	}

3.不推荐使用die、exit等PHP方法中断代码执行,推荐助手函数halt();

halt("中断输出");

===

06,基础、空、多级控制器

https://www.bilibili.com/video/BV12E411y7u8

一.基础控制器

1.一般来说,创建控制器后,推荐继承基础控制器来获得更多的方法;

2.基础控制器仅仅提供了控制器验证功能,并注入了thinkApp和think Request;

3.这两个对象后面会有章节详细讲解,下面我们继承并简单使用一下;

返回实际路径:$this->app->getBasePath();

返回当前方法名:$this->request->action();

use appBaseController;
class Test extends BaseController
{
	public function index()
	{
		//return "test-->index ";
		return "index,方法名:".$this->request->action().",当前实际路径:".$this->app->getBasePath();
	}
}

...

二.空控制器

1.在单应用模式下,我们可以给项目定义一个Error控制器类,来提醒错误;

namespace appcontroller;
class Error
{
	public function index(){
		return "当前控制器不存在!";
	}
}

当控制器为空时,就用此错误代替调试输出,友好信息。

...

三.多级控制器

1.所谓多级控制器,就是在控制器 controller目录下再建立目录并创建控制器;

2.我们在controller目录下建立group目录,并创建Blog.php控制器;

namespace appcontrollergroup;
use appBaseController;
class Blog
{
	public function index()	{
		return "Group-Blog-index";
	}
	public function read()	{
		return "Group-Blog-read";
	}
}
此时,我们需要访问的地址为: 
http://localhost:8000/group.blog
http://localhost:8000/group.blog/read

【版權聲明】
本文爲原創,遵循CC 4.0 BY-SA版權協議!轉載時請附上原文鏈接及本聲明。
原文鏈接:https://tdlib.com/am.php?t=2dBQ4BnMBdRy
Tag: Thinkphp Thinkphp笔记
歡迎評論
未登錄,
請先 [ 註冊 ] or [ 登錄 ]
(一分鍾即可完成註冊!)
返回首頁     ·   返回[Thinkphp]   ·   返回頂部