Home  >  Article  >  PHP Framework  >  What is laravel controller

What is laravel controller

青灯夜游
青灯夜游Original
2023-01-14 11:16:311518browse

In laravel, a controller (Controller) is a class used to implement certain functions; the controller can combine related request processing logic into a separate class. Some methods are stored in the controller to implement certain functions. The controller is called through routing, and callback functions are no longer used; the controller is stored in the "app/Http/Controllers" directory.

What is laravel controller

The operating environment of this tutorial: Windows 7 system, Laravel 6 version, DELL G3 computer.

Controller introduction

#1. What is a controller?

In order to replace all request processing logic defined in the form of closures in the route file, you may want to use control classes to organize this behavior. Controllers can group related request processing logic into a separate class.

Controller is a class used to implement certain functions. Some methods are stored in the controller to implement certain functions. The controller is called through routing, and callback functions are no longer used.

2. Where is the controller written?

App/Http/Controllers Place the controller

Controller.php is the parent class file, other controllers can inherit

3. How to name the controller file?

Humpbacked controller name Controller.php

For example, AddDataController.php LoginController.php

##4. Controller How to write the structure?

Automatically generated through the artisan command, for example: Make sure you are in the root directory of the current project and enter on the command line:

php artisan make:controller TestController

The structure code is automatically completed,

   namespace App\Http\Controller;
   use Illuminate\Http\Request;    
   class TestController extends  Controller{
     //
   }

Basic Controller

Define Controller

The following is an example of a basic controller class. It should be noted that this controller inherits the base controller of

Laravel. This class of controller provides some convenient methods, such as the middleware method, which can add middleware to the controller behavior:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
    /**
     * 显示指定用户的简介
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        return view(&#39;user.profile&#39;, [&#39;user&#39; => User::findOrFail($id)]);
    }
}

You can define a pointer to the controller behavior like this Routing:

use App\Http\Controllers\UserController;

Route::get(&#39;user/{id}&#39;, [UserController::class, &#39;show&#39;]);

When a request matches the URI of the specified route, the

show method in the UserController controller will be executed. Route parameters will also be passed to this method.

Tip: Controllers are not

required to inherit the base class. If a controller does not inherit from a base class, you will not be able to use some convenience features, such as the middleware, validate, and dispatch methods.

Single Behavior Controller

If you want to define a controller that only handles a single behavior, you can place a

__invoke Method:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class ShowProfile extends Controller
{
    /**
     * 显示指定用户的简介
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function __invoke($id)
    {
        return view(&#39;user.profile&#39;, [&#39;user&#39; => User::findOrFail($id)]);
    }
}

There is no need to specify the method when registering a route for a single behavior controller:

use App\Http\Controllers\ShowProfile;

Route::get(&#39;user/{id}&#39;, ShowProfile::class);

You can do this through

make in the Artisan command tool: The --invokable option in the controller command generates a callable controller

php artisan make:controller ShowProfile --invokable

Tips: You can use

stub to customize Custom control Controller template

Controller middleware

Middleware Routes that can be assigned to controllers in the route file:

Route::get(&#39;profile&#39;, [UserController::class, &#39;show&#39;])->middleware(&#39;auth&#39;);

However, it is more convenient to specify the middleware in the controller's constructor. Middleware can be easily assigned to a controller using the

middleware method in the controller's constructor. You can even limit middleware to only take effect on certain methods in the controller:

class UserController extends Controller
{
    /**
     * 实例化一个新的控制器实例
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(&#39;auth&#39;);

        $this->middleware(&#39;log&#39;)->only(&#39;index&#39;);

        $this->middleware(&#39;subscribed&#39;)->except(&#39;store&#39;);
    }
}

At the same time, the controller also allows you to use a closure to register middleware. This provides a convenient way to define middleware for a single controller without defining the entire middleware class:

$this->middleware(function ($request, $next) {
    // ...

    return $next($request);
});

Tip: You can assign the middleware to one of the controller actions Subset. However, it may be a sign that your controller is becoming complex. It is recommended that you split the controller into multiple smaller controllers.

Resource Controller

Laravel’s resource routing can allocate typical “CURD (Create, Delete, Modify, Check)” routes through a single line of code to the controller. For example, you want to create a controller that handles all HTTP requests for the Save Photos app. Use the Artisan command

make:controller to quickly create such a controller:

php artisan make:controller PhotoController --resource

This command will generate a controller

app/Http/Controllers/PhotoController.php . This includes methods for each available resource operation.

Next, you can register a resource route to the controller:

Route::resource(&#39;photos&#39;, PhotoController::class);

This single route declaration creates multiple routes to handle various behaviors on the resource. The generated controller retains methods for each action, including declarative annotations for handling HTTP verbs and URLs.

You can create multiple resource controllers at once by passing array parameters to the

resources method:

Route::resources([
    &#39;photos&#39; => PhotoController::class,
    &#39;posts&#39; => PostController::class,
]);

Resource Controller Operation deal with

Verb URI Action Route Name
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy

指定资源模型

如果你使用了路由模型绑定,并且想在资源控制器的方法中使用类型提示,你可以在生成控制器的时候使用 --model 选项:

php artisan make:controller PhotoController --resource --model=Photo

部分资源路由

当声明资源路由时,你可以指定控制器处理的部分行为,而不是所有默认的行为:

Route::resource(&#39;photos&#39;, PhotoController::class)->only([
    &#39;index&#39;, &#39;show&#39;
]);

Route::resource(&#39;photos&#39;, PhotoController::class)->except([
    &#39;create&#39;, &#39;store&#39;, &#39;update&#39;, &#39;destroy&#39;
]);

API 资源路由

当声明用于 APIs 的资源路由时,通常需要排除显示 HTML 模板的路由(如 createedit )。为了方便起见,你可以使用 apiResource 方法自动排除这两个路由:

Route::apiResource(&#39;photos&#39;, PhotoController::class);

你也可以传递一个数组给 apiResources 方法来同时注册多个 API 资源控制器:

Route::apiResources([
    &#39;photos&#39; => PhotoController::class,
    &#39;posts&#39; => PostController::class,
]);

要快速生成不包含 createedit 方法的用于开发接口的资源控制器,请在执行 make:controller 命令时使用 --api 参数:

php artisan make:controller API/PhotoController --api

嵌套资源

有时可能需要定义一个嵌套的资源型路由。例如,照片资源可能被添加了多个评论。那么可以在路由中使用 “点” 符号来声明资源型控制器:

Route::resource(&#39;photos.comments&#39;, PhotoCommentController::class);

该路由会注册一个嵌套资源,可以使用如下 URI 访问:

/photos/{photo}/comments/{comment}

限定嵌套资源的范围

Laravel 的 隐式模型绑定 特性可以自动限定嵌套绑定的范围,因此已解析的子模型会自动属于父模型。定义嵌套路由时,使用 scoped 方法,可以开启自动范围限定,也可以指定 Laravel 应该按照哪个字段检索子模型资源

Route::resource(&#39;photos.comments&#39;, PhotoCommentController::class)->scoped([
    &#39;comment&#39; => &#39;slug&#39;,
]);

这个路由会注册一个限定范围的嵌套资源路由,可以像下面这样来访问:

/photos/{photo}/comments/{comment:slug}

浅层嵌套

通常,并不完全需要在 URI 中同时拥有父 ID 和子 ID ,因为子 ID 已经是唯一的标识符。当使用唯一标识符(如自动递增的主键)来标识 URI 中的模型时,可以选择使用「浅嵌套」的方式定义路由:

Route::resource(&#39;photos.comments&#39;, CommentController::class)->shallow();

上面的路由定义方式会定义以下路由:

HTTP 方式 URI 行为 路由名称
GET /photos/{photo}/comments index photos.comments.index
GET /photos/{photo}/comments/create create photos.comments.create
POST /photos/{photo}/comments store photos.comments.store
GET /comments/{comment} show comments.show
GET /comments/{comment}/edit edit comments.edit
PUT/PATCH /comments/{comment} update comments.update
DELETE /comments/{comment} destroy comments.destroy

命名资源路由

默认情况下,所有的资源控制器行为都有一个路由名称。你可以传入 names 数组来覆盖这些名称:

Route::resource(&#39;photos&#39;, PhotoController::class)->names([
    &#39;create&#39; => &#39;photos.build&#39;
]);

命名资源路由参数

默认情况下,Route::resource 会根据资源名称的「单数」形式创建资源路由的路由参数。你可以在选项数组中传入 parameters 参数来轻松地覆盖每个资源。parameters 数组应该是资源名称和参数名称的关联数组:

Route::resource(&#39;users&#39;, AdminUserController::class)->parameters([
    &#39;users&#39; => &#39;admin_user&#39;
]);

上例将会为资源的 show 路由生成如下的 URI :

/users/{admin_user}

限定范围的资源路由

有时,在定义资源路由时隐式绑定了多个 Eloquent 模型,你希望限定第二个 Eloquent 模型必须为第一个 Eloquent 模型的子模型。例如,考虑这样一个场景,通过 slug 检索某个特殊用户的一篇文章:

use App\Http\Controllers\PostsController;Route::resource(&#39;users.posts&#39;, PostsController::class)->scoped();

你可以通过给 scoped 方法传递一个数组来覆盖默认的模型路由键:

use App\Http\Controllers\PostsController;Route::resource(&#39;users.posts&#39;, PostsController::class)->scoped([
    &#39;post&#39; => &#39;slug&#39;,
]);

当使用一个自定义键的隐式绑定作为嵌套路由参数时,Laravel 会自动限定查询范围,按照约定的命名方式去父类中查找关联方法,然后检索到对应的嵌套模型。在这种情况下,将假定 User 模型有一个叫 posts(路由参数名的复数)的关联方法,通过这个方法可以检索到 Post 模型。

本地化资源 URI

默认情况下,Route::resource 将会用英文动词创建资源 URI。如果需要自定义 createedit 行为的动作名,可以在 AppServiceProviderboot 中使用 Route::resourceVerbs 方法实现:

use Illuminate\Support\Facades\Route;

/**
 * 引导任何应用服务。
 *
 * @return void
 */
public function boot()
{
    Route::resourceVerbs([
        &#39;create&#39; => &#39;crear&#39;,
        &#39;edit&#39; => &#39;editar&#39;,
    ]);
}

动作被自定义后,像 Route::resource('fotos', 'PhotoController') 这样注册的资源路由将会产生如下的 URI:

/fotos/crear

/fotos/{foto}/editar

补充资源控制器

如果您需要增加额外的路由到默认的资源路由之中,您需要在 Route::resource 前定义它们;否则, resource 方法定义的路由可能会无意间优先于您定义的路由:

Route::get('photos/popular', [PhotoController::class, 'popular']);

Route::resource(&#39;photos&#39;, PhotoController::class);

技巧:记得保持您的控制器的专一性。如果您需要典型的资源操作以外的方法,请考虑将您的控制器分割为两个更小的控制器。

依赖注入 & 控制器

构造注入

Laravel 服务容器 被用于解析所有的 Laravel 控制器。因此,您可以在控制器的构造函数中使用类型提示需要的依赖项。声明的解析会自动解析并注入到控制器实例中去:

<?php

namespace App\Http\Controllers;

use App\Repositories\UserRepository;

class UserController extends Controller
{
    /**
     * 用户 repository 实例。
     */
    protected $users;

    /**
     * 创建一个新的控制器实例。
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
}

您亦可类型提示 Laravel 契约 ,只要它能够被解析。取决于您的应用,注入依赖到控制器可能会提供更好的可测试性。

方法注入

除了构造器注入以外,您亦可在控制器方法中类型提示依赖。最常见的用法便是注入 Illuminate\Http\Request 到您的控制器方法中:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 保存一个新用户。
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $name = $request->name;

        //
    }
}

如果您的控制器方法要从路由参数中获取输入内容,请在您的依赖项之后列出您的路由参数。例如,您可以像下方这样定义路由:

Route::put(&#39;user/{id}&#39;, [UserController::class, &#39;update&#39;]);

如下所示,您依然可以类型提示 Illuminate\Http\Request 并通过定义您的控制器方法访问 id 参数:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 修改指定的用户。
     *
     * @param  Request  $request
     * @param  string  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }
}

路由缓存

如果您的应用仅使用了基于路由的控制器,您应该充分利用 Laravel 路由缓存。使用路由缓存将会大幅降低您的应用路由的注册时间。有时,您的路由注册的速度可能会提高 100 倍。要生成路由缓存,仅需执行  route:cache Artisan 命令:

php artisan route:cache

在运行该命令后,每次请求将会加载您缓存的路由文件。请记住,您每次添加新路由后均需要生成新的路由缓存。因此,您应该在项目部署时才运行 route:cache 命令。

您亦可使用 route:clear 来清除路由缓存:

php artisan route:clear

【相关推荐:laravel视频教程

The above is the detailed content of What is laravel controller. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn