搜尋
首頁後端開發php教程Laravel 5文檔閱讀摘要

Laravel 5專案結構分析及中文文件閱讀摘要

 

中介軟體 5

控制器

7 HTTP 回應

8

Service Providers

11 Service Container

12

Facades

14

請求的生命週期

15

應用

應用認證20

緩存24

Artisan Console

26 擴充框架*

27

加密27

錯誤與日誌28

檔案系統 雲端儲存30

輔助方法 31

31

擴充包開發*31

分頁 隊列*

31 會話

323232

33單元測試*

35資料驗證

35資料驗證 36

查詢構造器38

結構產生器結構產生器遷移與資料填充

41

Eloquent ORM

41

 HTTP路由

基本路由基本路由

定義針對不同Http Method的路由,如:Route::

:: post('foo/bar', function(){('foo/bar', function(){Route::

match([ 多重方法

Route::any

('foo', function(){  # 所有方法使用方法生成方法

url

$url = url('foo');

 

Laravel會自動在每位使用者的session中放置隨機的tokenVerifyCsrfToken 中間件將保存在session中的請求和輸入的token配對。除了尋找CSRF token 作為「POST」參數,中間件也檢查X-XSRF-TOKEN請求頭。

插入

CSRF Token到表單type. " value="

csrf_token(); ?>">Blade模板引擎使用

:p _token" value="{{ csrf_token() }}">

加到X-XSRF-TOKEN

csrf-token" c/span>csrf_token() }}" />

.     headers: {

        '

X-CSRF-TOKEN': $('meta[name="csrf-token"]').. });

...

這樣所有

ajax請求中將會帶上該頭資訊:將會帶上該頭資訊

  url: "/foo/bar",})

方法欺騙

_method

" value="

PUT">

? ; ?>"> 

路由參數

基礎參數

Route::get('user/

{name?}

', function($name = null){ # 'user/{name?}', function(

$name = 'John'

){  #  帶預設值的參數){  #  

帶預設值的參數 可以定義參數的全局模式,在RouteServiceProviderboot方法定義模式:

之後,會作用在所有使用這個特定參數的路線上:

Route::get('user/{id

 if ($route->input('id') == 1){  

也可以透過依賴注入來取得參數:use IlluminateHttpRequest;

(<(He $request, $id ){    if ($request

->route('id')){

->route('id')){ Route::get(' user/profile', ['as' => 'profile'

, function(){ 

Route ::get('user/profile', [      

'as' => 'profile', 

'uses' 

 

使用命名路由進行重新導向

$url = route('profile'); ()->

route ('profile'); 

#  #   uteName();

 

路由群組

將共享屬性當作一個陣列當做Route:: 共用中間件

Route::group

(['middleware' => ['foo', 'bar'], 

=> ['foo', 'bar'], => ['foo', 'bar'],  Route::get('/', function()

    {

    }); 

    Route::get('user/profile', function()

    {  Middleware

    });

});

上例中

foo

自訂的中間件的鍵名與類別名稱映射關係需要在

Kernel.php中加入

 

共享命名空間

=p unction()

{    // Controllers Within The "AppHttpControllersAdmin" Namespace ute::group(['namespace' => 'User'], function()     {

        

    });

});

 子網域路由Route::group(['domain' => '

{account}.myapp.com'],   

    Route::get('user/{id}', function($account

, $

        //

    });

 

});

});

Route::group([

'prefix' 

=> 'admin'], function()

{

    Route:: 

        // Matches The "/admin/users" URL/admin/users

" URL

    });

在路由前綴中定義參數

Route::group(['prefix' => 'accounts/

{account_id}

'], function()

'], function()

   Route::get(' detail', function(

$account_id

)

                                                                 

Route model binding

model Binding provides a convenient way to inject model entities into routes

: Instead of injecting

User ID, you can choose to inject User

class entities that match the given ID

. Define model binding in the RouteServiceProvider::boot method:

public function boot(Router $router){ parent::boot($router ; {user} Parameter route:

Route::get('profile/{user}

', function(

AppUser $user){

) / /

});

A request to

profile/1 will inject the ID

for the 1 entityUser

. If the entity does not exist, throw 404. You can pass a closure as the third parameter to define the behavior when it is not found.

throws 404 error

Two methods:

abort (404); # Essentially throws a SymfonyComponentHttpKernelExceptionHttpException with a specific status code. Or: manually throw HttpException

middleware

New middleware

php artisan make:middleware OldMiddleware # Create a new middlewareThe main function of the middleware is implemented in the handle()

method:

class OldMiddleware {

public function handle($request, Closure $next){

if (xxx){

return

redirect('xx');

                                                                      🎙 }

Analyzing its structure, we can find that it is basically the execution Make a judgment, and then redirect or continue forward.

Global middleware

If you want the middleware to be executed by all HTTP requests, just add the middleware class to

app/Http/ Kernel.php

’s

$middleware property list.

Assign middleware to routing

After creating the new middleware, go to app/Http/Kernel.php

of

Add middle in $routeMiddleware The mapping relationship between the file key name and the class name, and then you can use this key name in routing to assign routes:

Route::get('admin/profile', ['middleware' =>

'auth', function(){

Terminable middleware

Terminable middleware needs to inherit from TerminableMiddleware

and implement terminate() Method. Its purpose is to execute after the HTTP response has been sent to the client. Terminable middleware needs to be added to the global middleware list of app/Http/Kernel.php .

Controller

Basic Controller

All controllers should extend the base controller class

use AppHttpControllers Controller;

class UserController extends Controller { # Inherits Controller

public function showProfile($id ) # Action

{

AppHttpControllersController is defined as follows:

namespace BorogadiHttpControllers;

use IlluminateFoundationBusDispatchesJobs;

use

IlluminateRoutingController

as BaseController;use IlluminateFoundationValidationValidatesRequests;

abstract class Controller extends BaseController

{

use DispatchesJobs, ValidatesRequests;

}It can be seen that it is ultimately inherited from the IlluminateRoutingController

class.

# Named controller route

Route::get('foo', ['uses' => 'FooController@method',

'as ' => 'name']);

# URL pointing to the controller

$url =

action('AppHttpControllersFooController@ method');

or:

URL::setRootControllerNamespace

('AppHttpControllers');

$url =

action('FooController@

Controller middleware

Two ways, one is to specify in the controller route:

Route::get('profile', [

'middleware'

=> 'auth',

'uses' => 'UserController@showProfile'

]);

The other is Specify directly in the controller constructor:

class UserController extends Controller { public function __construct(){

$this->middleware

(' auth');

$this->middleware

('log', ['only' => ['fooAction', 'barAction']]);

Implicit controller

Implicit controller implementation defines a single route to handle each behavior in the controller:

Define a route:

Route ::controller('users', 'UserController');

Define the implementation of the controller class:

class UserController extends BaseController {

Public function getIndex (){ # Response to

user

public function postProfile(){ # Response to

post way user/profile

Public function anyLogin(){ # Response to all methods of user/login

It is possible to support multi-word controller behavior by using "-": public function getAdminProfile() {} # Response to users/admin-profile , not user/adminprofile. Pay attention to the camel case naming method used in the action name

RESTfulResource controller

is actually a specific application of implicit controller.

Route cache

If only controller routing is used in the application, route caching can be used to improve performance.

php artisan route:cache

The cache route file will be used instead of the app/Http/routes.php file

HTTP request

Get the request

in two ways, one is through the Request facade:

use Request;

$name = Request::input('name');

or via dependency injection: use type hints on the class in the constructor or method in the controller. The currently requested instance will be automatically injected by the service container:

use IlluminateHttpRequest;

use IlluminateRoutingController;

class UserController extends Controller {

public function store(Request$request){

                                                   $name                                                                                                ​; request, $id

){

Get input data

$name = Request::input('name') ; # Get specific input data

$name = Request::input('name', 'Sally'); # Get specific input data, if not, get the default value

if (Request::has('name')){ # Confirm whether there is input data

$input = Request::all

();

# Get all input data$input = Request::only

('username', 'password');

# Get some input data $input = Request::except

('credit_card');

# Get partial input data exclusion method$input = Request::input('products.0.name'); # Get data in array form

old input data

Request::flash(); # Save the current input data into

session

Request::

flashOnly('username', 'email'); # Save some data into session Request::

flashExcept

('password'); # Save some data as session, elimination method

return redirect('form')->

withInput(); # Redirect and cache the current input data to session

return redirect('form')->withInput(Request::except('password')); # Redirect and cache part of the current input data to session

$username = Request::old('username'); # Get the one-time Session

{{ old(' username') }} # Showing old input data in bladetemplate

Cookies

L cookie created by aravel Encrypt and add authentication mark.

$value = Request::cookie('name'); # Get the Cookievalue

#In response Add Cookies

$response = new IlluminateHttpResponse('Hello World');

$response->withCookie (cookie('name', 'value' , $minutes));

$response->withCookie(cookie()->forever('name', 'value')); # Add Permanent Cookie

# Add Cookie in queue mode, that is, set Cookie before actually sending the response

Cookie::queue ('name', 'value');

return response('Hello World'); $file = Request: ; :file('photo')->isValid()) # Confirm whether the uploaded file is valid

Request::file('photo')->move($destinationPath); # Move Uploaded file

Request::file('photo')->move($destinationPath, $fileName); # Move the uploaded file and rename it

Other request information

$uri = Request::path(); # Get request

URI

if (Request::ajax())

# Determine whether a request uses AJAX

# Method to determine the request

$method = Request::method(); if (Request::isMethod('post'))

if (Request::is('admin/*')) #

Confirm whether the request path meets the specific format

$url = Request::url(); # Get request

URL

HTTP response

Basic responseRoute ::get('/', function(){ #

return string

return 'Hello World';

# Return to complete Responses

Instance, there are two methods

return Responses object:

use IlluminateHttpResponse;

return (new Response

($content, $status)) - ->header('Content-Type', $value);

or use response auxiliary Method:

return response($content, $status)->header('Content-Type', $value);

# Return to view

return response()-> return response($content)->

withCookie(

cookie('name', 'value'));

Redirect return redirect('user/login');

# Use

redirect

redirect method

return redirect ('user/login')-> ;with('message', 'Login Failed'); # Redirect and save the current data to Sessionreturn redirect()->back

() ; # Redirect to previous locationreturn redirect()->

route('login'); # Redirect to specific route

# Redirect to a specific route with parameters return redirect()->route('profile', [1]); #

routed

The URI

is:

profile/{id}

return redirect()->route('profile', ['user' => 1]); # routed URI is: profile/{user}

# Redirect based on controller actionreturn redirect()->action

('AppHttpControllersHomeController@index');

return redirect()->action('AppHttpControllersUserController@profile', ['user' => 1]); # With parameters

Other responses

# returnjson

return response()-> ;json(['name' => 'Abigail', 'state' => 'CA']); >json([' name' => 'Abigail', 'state' => 'CA'])

- ->setCallback($request->input('callback'));

#

File download

return response()->download($pathToFile, $name, $headers);

Response Macro

# Define the response macro, usually defined in the Provider method

Response::macro ('caps', function($value)

use ($response){ # PHP

By default, anonymous functions cannot call the context variables of the code block in which they are located, but need to use the

use

keyword.

use will copy a copy of the variable into the closure, and also supports reference forms, such as

use ( &$rmb )

return $response->make(strtoupper( $value));

});# Call the response macroreturn response()- >caps(' foo');

ViewBasic view

# View definition File path and file name: resources/views/greeting.php

                                                                                                      

#

View call

Route::get('/', function()

{

  return view( 'greeting'

, [

'name' => 'James']);

#

The parameter passed to the view is an array of key-value pairs});

#

Subfolder view call Definition location: resources/views/

admin/profile.php

return view(' admin.profile ', $data);

# Other ways to pass data to the view

$view = view('greeting')->

with

( 'name', 'Victoria'); # Traditional method

$view = view('greeting')->withName('Victoria'); # Magic Method

$view = view('greetings', $data); # Directly pass the array $data is an array of key-value pairs

# Share data to all views

Customize a Provider

, or add directly in the

boot method of AppServiceProvider

:

view( )->share('data', [1, 2, 3]); or:

View::share('data', [1, 2 , 3]);

# Confirm whether the view exists

if (view()->exists

('emails .customer'))

# Generate a view from a file path

return view()->file

($pathToFile, $data);

View componentView component is a closure or class method that is called before the view is rendered.

#

Define view components

use View;

use IlluminateSupportServiceProvider; View::

composer

('profile', 'AppHttpViewComposersProfileComposer'); #指 Use a class to specify the view component

View ::

composer ('dashboard', function ($ view) {

# Use closure to specify the view component

...

                                                              Use classes to specify view components, The method named compose of the specified class will be called before the view is rendered. As in the above example, the

ProfileComposer'

class is defined as:

use IlluminateContractsViewView;

use IlluminateUsersRepository as UserRepository;

class ProfileComposer {

protected $users;

public function __construct(UserRepository $users){ # service container will automatically parse the required parameters

                                           

Public function

compose(View $view){

# The compose method is passed an instance of View, where parameters can be passed to View          $ view->with('count', $this->users->count());

}

}

#

Using wildcards within the view component

View::composer('*', function($view){ # is equivalent to defining it for all views

#

Attach view components to multiple views at the same time

View::composer(['profile', 'dashboard'], 'AppHttpViewComposersMyViewComposer');

#

Many definitions View components

View::composers([

'AppHttpViewComposersAdminComposer' => ['admin.index', 'admin.profile'],

'AppHttpViewComposersUserComposer ' => 'user',

'AppHttpViewComposersProductComposer' => 'product'

]);

Service Providers

Each custom Provider must inherit from

IlluminateSupport

ServiceProvider and be registered in the Providers array in config/app.php. The custom Provider must define the register() method, which is used to define the behavior during registration. In addition, there are two optional methods and an optional attribute: the boot() method will not be called until all Provider have been loaded, and the provides()method Used in conjunction with the $defer optional attribute to provide the buffering function. The idea of ​​​​providing services through service providers: implement a class that completes the actual work, define a Provider, and use it in the

register()

method of Provider Methods to register the actual work class with the system container and obtain the actual work class instance. Then register this Provider in the application configuration. In this way, the register() method of all Provider will be called when the application is initialized to indirectly register the way to obtain the actual working class instance. #

Define a basic

Provider

use RiakConnection;

use IlluminateSupportServiceProvider ) # Register a class in the container and obtain its instance Method

                                                                                                                              Return new Connection($app['config' ]['riak']);

                                             ; Service Container

Basic usage

in Inside the

Provider

, the service container can be accessed through

$this->app

.

There are two main ways to register dependencies: callback interface method and binding instance interface.

# The way of closure callback$this->app->bind('FooBar', function($app){

Return new FooBar($app['SomethingElse']);

});

# Registered as a singleton, subsequent calls will return the same instance

$this->app->singleton('FooBar', function($app){

return new FooBar($app['SomethingElse']);

});

#

Bind to an existing instance

$fooBar = new FooBar(new SomethingElse);

$this ->app->instance('FooBar', $fooBar);

There are two ways to resolve the instance from the container:

$fooBar = $this-> ;app->make('FooBar');

# Use the make()

method to parse

$fooBar = $this->app['FooBar'];

# Because the container implements the ArrayAccess

interface, you can use the array access form After defining the registration and parsing information, you can directly use it in the constructor of the class Specify the required dependencies via type-hint

, and the container will automatically inject all the required dependencies.

use IlluminateRoutingController; AppUsersRepository as UserRepository;class UserController extends Controller {

protected $users;

public function __construct(

UserRepository $users){

# type-hint

                                                                                                                              $users;

}

public function show($id){

}

}

Binding interface

interface

EventPusher

{

Public function push($event, array $data);

}

class

PusherEventPusher

implements EventPusher {

...

}

Because the PusherEventPusher

class implements EventPusher Interface, so you can directly register this interface and bind it to a class that implements this interface: $this->app->

bind

('AppContractsEventPusher', 'AppServicesPusherEventPusher ');

When a class requires the EventPusher interface, it will tell the container that it should inject

PusherEventPusher.

Context binding

$this->app->when

('AppHandlersCommandsCreateOrderHandler')

                                                                  needs('AppContractsEventPusher')                                                           tPusher');

tag

$this->app->bind('SpeedReport', function(){

});

$this->app->bind ('MemoryReport', function (){

}); reports');

#

Tag the class registered in the previous two steps as 'reports'

Parse them properly:

$this->app->bind('ReportAggregator', function($app){ ) return new ReportAggregator($app->tagged ('reports'));

});

Container events

The container will trigger an event when parsing each object. You can use the resolving method to listen for this event (the parsed object will be passed into the closure method):

$this->app->resolving(function($object, $app){ # Called when the container resolves any type of dependency

...

});$this->app- >resolving(function(FooBar $fooBar, $app){ #

Called when the container resolves a dependency of type

'FooBar'

...

});

Contracts

Contracts is the interface used by all

Laravel

main component implementations , you can see it under the Contracts

directory The directory structure is the same as in

Illuminate.

Contracts

is the interface definition,

Illuminate

is the specific implementation. Each concrete implemented class in Illuminate

extends its corresponding interface in

Contracts. This separation of interface and implementation can make dependency injection low-coupling. /laravel/framework/src

/Illuminate

/Auth

/Broadcasting

/Bus

...

/Contracts

/Auth

/Broadcasting

/Bus

...

FacadesBasic usage

Facades provide a static interface to classes that can be accessed in the application's

service container. (An application of "decoration mode" in design pattern mainly uses class_alias

to create category names, and also uses

__callStatic() to provide a static proxy, which is ultimately simulated using a mock object

PHP

object and call the object's method)

Laravel's facades and any custom facades you create, will inherit the base class Facade and only need to implement one method: getFacadeAccessor() .

Such as CacheThis facade is called: $value = Cache::get( 'key');

Look at the implementation of the class:

class Cache extends Facade {

protected static function getFacadeAccessor() { return 'cache'; } # This The function of the method is to return the name of the service container binding

}

When the user executes any static method on the Cache's facade, Laravel Will resolve the bound cache from the service container and execute the requested method (in this example, get)

on that object All facades exist in the global namespace. When used in a nested namespace, you need to import the facade class into the namespace:

use Cache; # ImportCache facade

class PhotosController extends Controller {

public function index(){

$ photos = Cache::get('photos');

}

}

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
超越炒作:評估當今PHP的角色超越炒作:評估當今PHP的角色Apr 12, 2025 am 12:17 AM

PHP在現代編程中仍然是一個強大且廣泛使用的工具,尤其在web開發領域。 1)PHP易用且與數據庫集成無縫,是許多開發者的首選。 2)它支持動態內容生成和麵向對象編程,適合快速創建和維護網站。 3)PHP的性能可以通過緩存和優化數據庫查詢來提升,其廣泛的社區和豐富生態系統使其在當今技術棧中仍具重要地位。

PHP中的弱參考是什麼?什麼時候有用?PHP中的弱參考是什麼?什麼時候有用?Apr 12, 2025 am 12:13 AM

在PHP中,弱引用是通過WeakReference類實現的,不會阻止垃圾回收器回收對象。弱引用適用於緩存系統和事件監聽器等場景,需注意其不能保證對象存活,且垃圾回收可能延遲。

解釋PHP中的__ Invoke Magic方法。解釋PHP中的__ Invoke Magic方法。Apr 12, 2025 am 12:07 AM

\_\_invoke方法允許對象像函數一樣被調用。 1.定義\_\_invoke方法使對象可被調用。 2.使用$obj(...)語法時,PHP會執行\_\_invoke方法。 3.適用於日誌記錄和計算器等場景,提高代碼靈活性和可讀性。

解釋PHP 8.1中的纖維以進行並發。解釋PHP 8.1中的纖維以進行並發。Apr 12, 2025 am 12:05 AM

Fibers在PHP8.1中引入,提升了並發處理能力。 1)Fibers是一種輕量級的並發模型,類似於協程。 2)它們允許開發者手動控制任務的執行流,適合處理I/O密集型任務。 3)使用Fibers可以編寫更高效、響應性更強的代碼。

PHP社區:資源,支持和發展PHP社區:資源,支持和發展Apr 12, 2025 am 12:04 AM

PHP社區提供了豐富的資源和支持,幫助開發者成長。 1)資源包括官方文檔、教程、博客和開源項目如Laravel和Symfony。 2)支持可以通過StackOverflow、Reddit和Slack頻道獲得。 3)開發動態可以通過關注RFC了解。 4)融入社區可以通過積極參與、貢獻代碼和學習分享來實現。

PHP與Python:了解差異PHP與Python:了解差異Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

php:死亡還是簡單地適應?php:死亡還是簡單地適應?Apr 11, 2025 am 12:13 AM

PHP不是在消亡,而是在不斷適應和進化。 1)PHP從1994年起經歷多次版本迭代,適應新技術趨勢。 2)目前廣泛應用於電子商務、內容管理系統等領域。 3)PHP8引入JIT編譯器等功能,提升性能和現代化。 4)使用OPcache和遵循PSR-12標準可優化性能和代碼質量。

PHP的未來:改編和創新PHP的未來:改編和創新Apr 11, 2025 am 12:01 AM

PHP的未來將通過適應新技術趨勢和引入創新特性來實現:1)適應云計算、容器化和微服務架構,支持Docker和Kubernetes;2)引入JIT編譯器和枚舉類型,提升性能和數據處理效率;3)持續優化性能和推廣最佳實踐。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用