国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

<thead id="w68qb"><optgroup id="w68qb"></optgroup></thead>
  • <noframes id="w68qb"><table id="w68qb"></table></noframes>
    <small id="w68qb"><source id="w68qb"></source></small>
    Table of Contents
    Controller introduction
    Basic Controller
    Controller middleware
    Resource Controller
    部分資源路由" >部分資源路由
    嵌套資源
    命名資源路由
    命名資源路由參數(shù)
    限定范圍的資源路由
    本地化資源 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);

    你也可以傳遞一個數(shù)組給 apiResources 方法來同時注冊多個 API 資源控制器:

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

    要快速生成不包含 createedit 方法的用于開發(fā)接口的資源控制器,請在執(zhí)行 make:controller 命令時使用 --api 參數(shù):

    php artisan make:controller API/PhotoController --api

    嵌套資源

    有時可能需要定義一個嵌套的資源型路由。例如,照片資源可能被添加了多個評論。那么可以在路由中使用 “點” 符號來聲明資源型控制器:

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

    該路由會注冊一個嵌套資源,可以使用如下 URI 訪問:

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

    限定嵌套資源的范圍

    Laravel 的 隱式模型綁定 特性可以自動限定嵌套綁定的范圍,因此已解析的子模型會自動屬于父模型。定義嵌套路由時,使用 scoped 方法,可以開啟自動范圍限定,也可以指定 Laravel 應(yīng)該按照哪個字段檢索子模型資源

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

    這個路由會注冊一個限定范圍的嵌套資源路由,可以像下面這樣來訪問:

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

    淺層嵌套

    通常,并不完全需要在 URI 中同時擁有父 ID 和子 ID ,因為子 ID 已經(jīng)是唯一的標識符。當使用唯一標識符(如自動遞增的主鍵)來標識 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 數(shù)組來覆蓋這些名稱:

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

    命名資源路由參數(shù)

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

    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 方法傳遞一個數(shù)組來覆蓋默認的模型路由鍵:

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

    當使用一個自定義鍵的隱式綁定作為嵌套路由參數(shù)時,Laravel 會自動限定查詢范圍,按照約定的命名方式去父類中查找關(guān)聯(lián)方法,然后檢索到對應(yīng)的嵌套模型。在這種情況下,將假定 User 模型有一個叫 posts(路由參數(shù)名的復(fù)數(shù))的關(guān)聯(lián)方法,通過這個方法可以檢索到 Post 模型。

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

    use Illuminate\Support\Facades\Route;
    
    /**
     * 引導(dǎo)任何應(yīng)用服務(wù)。
     *
     * @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;) 這樣注冊的資源路由將會產(chǎn)生如下的 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);

    技巧:記得保持您的控制器的專一性。如果您需要典型的資源操作以外的方法,請考慮將您的控制器分割為兩個更小的控制器。

    依賴注入 & 控制器

    構(gòu)造注入

    Laravel 服務(wù)容器 被用于解析所有的 Laravel 控制器。因此,您可以在控制器的構(gòu)造函數(shù)中使用類型提示需要的依賴項。聲明的解析會自動解析并注入到控制器實例中去:

    <?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 契約 ,只要它能夠被解析。取決于您的應(yīng)用,注入依賴到控制器可能會提供更好的可測試性。

    方法注入

    除了構(gòu)造器注入以外,您亦可在控制器方法中類型提示依賴。最常見的用法便是注入 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;
    
            //
        }
    }

    如果您的控制器方法要從路由參數(shù)中獲取輸入內(nèi)容,請在您的依賴項之后列出您的路由參數(shù)。例如,您可以像下方這樣定義路由:

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

    如下所示,您依然可以類型提示 Illuminate\Http\Request 并通過定義您的控制器方法訪問 id 參數(shù):

    <?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)
        {
            //
        }
    }

    如果您的應(yīng)用僅使用了基于路由的控制器,您應(yīng)該充分利用 Laravel 路由緩存。使用路由緩存將會大幅降低您的應(yīng)用路由的注冊時間。有時,您的路由注冊的速度可能會提高 100 倍。要生成路由緩存,僅需執(zhí)行 route:cache Artisan 命令:

    php artisan route:cache

    在運行該命令后,每次請求將會加載您緩存的路由文件。請記住,您每次添加新路由后均需要生成新的路由緩存。因此,您應(yīng)該在項目部署時才運行 route:cache 命令。

    您亦可使用 route:clear 來清除路由緩存:

    php artisan route:clear

    【相關(guān)推薦: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)

    How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

    TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

    What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

    The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

    How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

    Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

    How to quickly test PHP code snippets? How to quickly test PHP code snippets? Jun 25, 2025 am 12:58 AM

    ToquicklytestaPHPcodesnippet,useanonlinePHPsandboxlike3v4l.orgorPHPize.onlineforinstantexecutionwithoutsetup;runcodelocallywithPHPCLIbycreatinga.phpfileandexecutingitviatheterminal;optionallyusephp-rforone-liners;setupalocaldevelopmentenvironmentwith

    How do I prevent cross-site request forgery (CSRF) attacks in PHP? How do I prevent cross-site request forgery (CSRF) attacks in PHP? Jun 28, 2025 am 02:25 AM

    TopreventCSRFattacksinPHP,implementanti-CSRFtokens.1)Generateandstoresecuretokensusingrandom_bytes()orbin2hex(random_bytes(32)),savethemin$_SESSION,andincludetheminformsashiddeninputs.2)ValidatetokensonsubmissionbystrictlycomparingthePOSTtokenwiththe

    How to upgrade PHP version? How to upgrade PHP version? Jun 27, 2025 am 02:14 AM

    Upgrading the PHP version is actually not difficult, but the key lies in the operation steps and precautions. The following are the specific methods: 1. Confirm the current PHP version and running environment, use the command line or phpinfo.php file to view; 2. Select the suitable new version and install it. It is recommended to install it with 8.2 or 8.1. Linux users use package manager, and macOS users use Homebrew; 3. Migrate configuration files and extensions, update php.ini and install necessary extensions; 4. Test whether the website is running normally, check the error log to ensure that there is no compatibility problem. Follow these steps and you can successfully complete the upgrade in most situations.

    Caching Strategies | Optimizing Laravel Performance Caching Strategies | Optimizing Laravel Performance Jun 27, 2025 pm 05:41 PM

    CachinginLaravelsignificantlyimprovesapplicationperformancebyreducingdatabasequeriesandminimizingredundantprocessing.Tousecachingeffectively,followthesesteps:1.Useroutecachingforstaticrouteswithphpartisanroute:cache,idealforpublicpageslike/aboutbutno

    PHP beginner guide: Detailed explanation of local environment configuration PHP beginner guide: Detailed explanation of local environment configuration Jun 27, 2025 am 02:09 AM

    To set up a PHP development environment, you need to select the appropriate tools and install the configuration correctly. ①The most basic PHP local environment requires three components: the web server (Apache or Nginx), the PHP itself and the database (such as MySQL/MariaDB); ② It is recommended that beginners use integration packages such as XAMPP or MAMP, which simplify the installation process. XAMPP is suitable for Windows and macOS. After installation, the project files are placed in the htdocs directory and accessed through localhost; ③MAMP is suitable for Mac users and supports convenient switching of PHP versions, but the free version has limited functions; ④ Advanced users can manually install them by Homebrew, in macOS/Linux systems

    See all articles