Blogger Information
Blog 2
fans 0
comment 0
visits 3487
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月22日作业---1.控制器,请求对象 2.依赖注入
土豆的博客
Original
792 people have browsed it

控制器

按照ThinkPHP的架构设计,所有的URL请求(无论是否采用了路由),最终都会定位到控制器(也许实际的类不一定是控制器类,但也属于广义范畴的控制器)。

  • 控制器定义

控制器文件通常放在application/module/controller下面,类名和文件名保持大小写一致,并采用驼峰命名(首字母大写)。

一个典型的控制器类定义如下:

实例

<?php
namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
    public function index()
    {
        return 'index';
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

控制器类文件的实际位置是

application\index\controller\Index.php

访问URL地址是(假设没有定义路由的情况下)

http://localhost/index.php/index
  • 渲染输出

默认情况下,控制器的输出全部采用return的方式,无需进行任何的手动输出,系统会自动完成渲染内容的输出。

下面都是有效的输出方式:

实例

<?php
namespace app\index\controller;

class Index 
{
    public function hello()
    {
    	// 输出hello,world!
        return 'hello,world!';
    }
    
    public function json()
    {
    	// 输出JSON
        return json_encode($data);
    }
    
    public function read()
    {
    	// 渲染默认模板输出
        return view();
    }

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

请求对象

当前的请求对象由think\Request类负责,在很多场合下并不需要实例化调用,通常使用依赖注入即可。在其它场合(例如模板输出等)则可以使用think\facade\Request静态类操作。

  • 请求对象调用

在控制器中通常情况下有两种方式进行依赖注入。

构造方法注入

操作方法注入

  • Facade调用

在没有使用依赖注入的场合,可以通过Facade机制来静态调用请求对象的方法(注意use引入的类库区别)。

实例

<?php

namespace app\index\controller;

use think\Controller;
use think\facade\Request;

class Index extends Controller
{
    
    public function index()
    {
		return Request::param('name');
    }    
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

依赖注入

依赖注入其实本质上是指对类的依赖通过构造器完成自动注入,例如在控制器架构方法和操作方法中一旦对参数进行对象类型约束则会自动触发依赖注入,由于访问控制器的参数都来自于URL请求,普通变量就是通过参数绑定自动获取,对象变量则是通过依赖注入生成。

实例

<?php
namespace app\index\controller;

use app\index\model\User;

class Index
{
    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function hello()
    {
        return 'Hello,' . $this->user->name . '!';
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!