亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Controller introduction
Basic Controller
Controller middleware
Resource Controller
部分資源路由" >部分資源路由
嵌套資源
命名資源路由
命名資源路由參數
限定范圍的資源路由
本地化資源 URI" >本地化資源 URI
補充資源控制器
依賴注入 & 控制器
路由緩存" >路由緩存
Home PHP Framework Laravel What is laravel controller

What is laravel controller

Jan 14, 2023 am 11:16 AM
php laravel controller

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

VerbURIActionRoute Name
GET/photosindexphotos.index
GET/photos/createcreatephotos.create
POST/photosstorephotos.store
GET/photos/{photo}showphotos.show
GET/photos/{photo}/editeditphotos.edit
PUT/PATCH/photos/{photo}updatephotos.update
DELETE/photos/{photo}destroyphotos.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 方法的用于開發(fā)接口的資源控制器,請在執(zhí)行 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}/commentsindexphotos.comments.index
GET/photos/{photo}/comments/createcreatephotos.comments.create
POST/photos/{photo}/commentsstorephotos.comments.store
GET/comments/{comment}showcomments.show
GET/comments/{comment}/editeditcomments.edit
PUT/PATCH/comments/{comment}updatecomments.update
DELETE/comments/{comment}destroycomments.destroy

命名資源路由

默認情況下,所有的資源控制器行為都有一個路由名稱。你可以傳入 names 數組來覆蓋這些名稱:

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

命名資源路由參數

默認情況下,Route::resource 會根據資源名稱的「單數」形式創(chuàng)建資源路由的路由參數。你可以在選項數組中傳入 parameters 參數來輕松地覆蓋每個資源。parameters 數組應該是資源名稱和參數名稱的關聯(lián)數組:

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 會自動限定查詢范圍,按照約定的命名方式去父類中查找關聯(lián)方法,然后檢索到對應的嵌套模型。在這種情況下,將假定 User 模型有一個叫 posts(路由參數名的復數)的關聯(lián)方法,通過這個方法可以檢索到 Post 模型。

默認情況下,Route::resource 將會用英文動詞創(chuàng)建資源 URI。如果需要自定義 createedit 行為的動作名,可以在 AppServiceProviderboot 中使用 Route::resourceVerbs 方法實現(xiàn):

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(&#39;fotos&#39;, &#39;PhotoController&#39;) 這樣注冊的資源路由將會產生如下的 URI:

/fotos/crear

/fotos/{foto}/editar

補充資源控制器

如果您需要增加額外的路由到默認的資源路由之中,您需要在 Route::resource 前定義它們;否則, resource 方法定義的路由可能會無意間優(yōu)先于您定義的路由:

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;

    /**
     * 創(chuàng)建一個新的控制器實例。
     *
     * @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 倍。要生成路由緩存,僅需執(zhí)行 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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Object-Relational Mapping (ORM) Performance Tuning in PHP Object-Relational Mapping (ORM) Performance Tuning in PHP Jul 29, 2025 am 05:00 AM

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

Creating Production-Ready Docker Environments for PHP Creating Production-Ready Docker Environments for PHP Jul 27, 2025 am 04:32 AM

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment

Building Resilient Microservices with PHP and RabbitMQ Building Resilient Microservices with PHP and RabbitMQ Jul 27, 2025 am 04:32 AM

To build a flexible PHP microservice, you need to use RabbitMQ to achieve asynchronous communication, 1. Decouple the service through message queues to avoid cascade failures; 2. Configure persistent queues, persistent messages, release confirmation and manual ACK to ensure reliability; 3. Use exponential backoff retry, TTL and dead letter queue security processing failures; 4. Use tools such as supervisord to protect consumer processes and enable heartbeat mechanisms to ensure service health; and ultimately realize the ability of the system to continuously operate in failures.

Building Immutable Objects in PHP with Readonly Properties Building Immutable Objects in PHP with Readonly Properties Jul 30, 2025 am 05:40 AM

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

The Serverless Revolution: Deploying Scalable PHP Applications with Bref The Serverless Revolution: Deploying Scalable PHP Applications with Bref Jul 28, 2025 am 04:39 AM

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

A Deep Dive into PHP's Internal Garbage Collection Mechanism A Deep Dive into PHP's Internal Garbage Collection Mechanism Jul 28, 2025 am 04:44 AM

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

See all articles