thinkphp 컨트롤러의 정의와 사용법을 자세히 설명한 글

藏色散人
풀어 주다: 2021-08-25 09:01:57
앞으로
3989명이 탐색했습니다.

다음은 thinkphpframework 튜토리얼 칼럼에서 thinkphp 컨트롤러의 정의와 사용법을 소개한 내용입니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

컨트롤러 정의

클래스 이름은 파일 이름과 동일합니다.

Rendering Output

Rendering Output은 return Output을 사용합니다

<?php namespace app\admin\controller;
use app\admin\model\User;

class Index
{

    public function Index(){
        $data = array(
            &#39;ming&#39; => 'ming',
            'ming' => 'xiao'
        );
        return json($data);
    }

}
로그인 후 복사

이때 페이지에서는 json 파일을 렌더링합니다
thinkphp 컨트롤러의 정의와 사용법을 자세히 설명한 글

컨트롤러 인터럽트 코드에는 포함될 수 없습니다. .
정지 출력 사용

<?php namespace app\admin\controller;
use app\admin\model\User;

class Index
{

    public function Index(){
        $data = array(
            &#39;ming&#39; => 'ming',
            'ming' => 'xiao'
        );
        halt("输出测试");
        return json($data);
    }

}
로그인 후 복사

정지 출력 사용

thinkphp 컨트롤러의 정의와 사용법을 자세히 설명한 글

다단계 컨트롤러

다단계 컨트롤러 다단계 컨트롤러는 네임스페이스에서 직접 사용됩니다.

<?php namespace app\admin\controller\Index;


class Blog
{
    public function index(){

    }

    public function read($id){
        var_dump(url(&#39;index/blog/read&#39;, [&#39;id&#39; => 5, 'name' => 'ming']));
        return $id;
    }
}
로그인 후 복사

인덱스 네임스페이스 아래 하위 컨트롤러 블로그를 정의합니다
디렉토리 구조
thinkphp 컨트롤러의 정의와 사용법을 자세히 설명한 글

라우팅 규칙 정의

<?php use think\facade\Route;

Route::rule(&#39;blog/:id&#39;, &#39;index.blog/read&#39;);
Route::rule(&#39;/&#39;, &#39;Index/index&#39;);
로그인 후 복사

인덱스 경로 아래의 블로그 디렉토리에 액세스

기본 컨트롤러

컨트롤러에는 기본 컨트롤러가 있습니다
시스템은

app\BaseController
로그인 후 복사

기본 컨트롤러

를 제공합니다.디렉토리 파일은 다음과 같습니다.
thinkphp 컨트롤러의 정의와 사용법을 자세히 설명한 글

다중 응용 프로그램 모드로 인해 모든 컨트롤에는 기본 컨트롤 클래스인
appBaseController

가 있습니다. . 기본 클래스가 디렉터리로 이동
thinkphp 컨트롤러의 정의와 사용법을 자세히 설명한 글

네임스페이스 변경

namespace app\index\controller;

use think\App;
use think\exception\ValidateException;
use think\Validate;
로그인 후 복사
<?php namespace app\index\controller;

use think\Request;

class Index extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $action = $this->request->action();
        $path = $this->app->getBasePath();
        var_dump($action);
        var_dump($path);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
로그인 후 복사

출력 내용

string(5) "index" string(43) "/home/ming/PhpstormProjects/untitled12/app/"
로그인 후 복사

컨트롤러 검증

<?php namespace app\index\controller;

use think\exception\ValidateException;
use think\Request;

class Index extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        try {
            $this->validate( [
                'name'  => 'thinkphp',
                'email' => 'thinkphp@qq.com',
            ],  'app\index\validate\User');
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            dump($e->getError());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
로그인 후 복사

이런 식으로 컨트롤러가 검증됩니다

빈 컨트롤러

빈 컨트롤러는 메서드가

    public function __call($name, $arguments)
    {
        // TODO: Implement __call() method.
        return 'error request';
    }
로그인 후 복사

리소스 컨트롤러라는 메소드

안정적인 컨트롤러 생성
Input

php think make:controller index@Blog
로그인 후 복사

리소스 컨트롤러 생성
api 생성

<?php namespace app\index\controller;

use think\Request;

class Blog
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
로그인 후 복사

리소스 라우팅 등록

Route::resource('blog', 'Blog');
로그인 후 복사

컨트롤러 미들웨어

컨트롤러 쓰기

<?php namespace app\index\middleware;

class Hello
{
    public function handle($request, \Closure $next){
        $request->hello = 'ming';
        return $next($request);
    }
}
로그인 후 복사

라우트 등록 컨트롤러 사용

<?php use think\facade\Route;

Route::rule(&#39;ming&#39;, &#39;index/index&#39;)->middleware(
    [
        app\index\middleware\Hello::class
    ]
);
로그인 후 복사

http://localhost:8082/index/ming
ming

이 나타나면 미들웨어 등록이 성공한 것입니다.

위 내용은 thinkphp 컨트롤러의 정의와 사용법을 자세히 설명한 글의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:segmentfault.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!