On the PHP framework of eight days to learn basic functions day5

 

Content Framework very much, if carefully study it again, then, one day is not enough. So I chose to study targeted content we need, roughly routing, middleware, controller three core parts. Even if only three parts, nor is it takes only three hours will be able to grasp, so be prepared. More time to learn.

In fact, at work, the most frequent contact is the framework. The contents of the previous study, are laying the foundation for the learning framework. But based on my experience and my personal point of view, the framework is not the core of things, but the most important thing. So to explain: the water framework, iron programming language. Beyond that the talk: programming language, compiler theory iron water. So in addition to spare time I learn programming languages ​​and frameworks, but also still learning to compile school.

We need to understand that the framework can be achieved, programming languages ​​can be achieved. Linguistic Programming is not good, you do not know the frame are doing. Framework exists to use a unified approach to rapidly develop and manage our applications. Do not let the frame become resistance you learn programming language.

In my short career, I encountered not only with Spring and Java's Java engineers have also experienced front-end engineers will use jQuery and JavaScript are not. I hope we will not be such a person.

Debate on the framework and programming languages, I have not been stopped. I do not care how other people think, I still own all of the requirements of the first, the second frame ideological programming language. As I never rote API framework, commonly used form muscle memory, do not back down common waste of brain space, as a direct look through official documents.

 

First, routing

What is routing?

wikipedia answers given on: the route is a network route selection between a plurality of networks or between or process.

In a real web applications, routing configuration by routing table, it determines the address you entered from the browser, which corresponds to the implementation of thing, what resources are returned.

The simplest is the windows hosts file is a routing table configuration.

Laravel routing content is very much, I put most commonly used to write Demo.

Routing configuration laravel two types, one is api configurations, one configuration page. We do not need to configure the page, so only concern api configuration.

Been mentioned in the last chapter, routing configuration table in the project root directory routes, api.php document represents api routing configuration. Our code in this file.

You can use a tool like the postman on the route to be tested.

Basic routing

Basic routing using Illuminate\Support\Facades\Routestatic methods of this class is created. This method takes two parameters, the first one is the route name, the second is a callback function.

Route::get('route1', function () {
    return 'hello route1';
});

The above operation is the basic code based routing. Access http://homestead.test/api/route24will be able to get content.

Why api here with a prefix it? The purpose is to distinguish and page routing.

We can change this prefix, such as adding a version number.

In the app / providers / RouteServiceProvider.php, find the mapApiRoutesmethod, there api defines the prefix route. We can add a v1 is the version 1, so you need http://homestead.test/api/v1/route24to visit.

protected function mapApiRoutes()
    {
        Route::prefix('api/v1')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

The above route1 routing only way to get support request, you can try using a post mode request, you will get an error.

The POST method is not supported for this route. Supported methods: GET, HEAD.

This means that the route does not support the post method, it supports only get method requests.

Then we can write a post of routing.

Route::post('route2', function () {
    return 'hello route2';
});

The above request routing support post method.

laravel embodiment supports a total of six kinds of requests, these methods have a corresponding static method Route class:

  • get

  • post

  • put

  • patch

  • delete

  • options

If you want to create a routing supports both get and post, you can use the match method accepts three parameters. The first one is an array of strings, includes support for the request method, the second is the route name, the third is the callback function .

Route::match(['get', 'post'], "route3", function () {
    return 'hello route3';
});

If you want to create a route all the way to support, you can use any method.

Route::any('route4', function () {
    return "hello route4";
});
Redirect

Use redirect method. This will enable route5 redirected to route4.

Route::redirect('route5', 'route4');

Redirect the default status code is 302. We can use the first three parameters specify their own, such as 301

Route::redirect('route6', 'route4', 301);

In addition, the method may also be used permanentRedirect, and code the same as the above effect.

Road :: permanentRedirect ( 'route7', 'Route4');

Routing parameters

Required parameters

Use {} package, this parameter is automatically injected into the callback function.

Route::get('/route8/{id}', function ($id) {
    return 'id:' . $id;
});
Optional parameters

Plus after the parameter name?. You must have a default value, or will be error

Route::get('/route9/{id?}', function ($id = 1) {
    return 'id:' . $id;
});
Using regular constraint parameters
Route::get('route10/{id}', function ($id) {
    return 'id:' . $id;
})->where('id', '[A-Za-z]+');

Only route10 / a parameter such routing in response to the request letter, route10 / 1 This route may not match the numerical parameters.

If you want to make global constraints, set the boot method app / Providers / RouteServiceProvider in the middle. For example, all routing parameter named id only support digital.

public function boot()
{
    Route::pattern('id', '[0-9]+');
​
    parent::boot();
}

If there is a global setting, and that there is a method where, where will override the global settings.

Route name life

Chained method calls the name.

Route::get('route11/info', function () {
    return 'route 11 info';
})->name('info');

So route11/infothe route's name is info.

Re-routed through the route will be able to get this method.$url = route('info');

Back from the retreat

For processing all other routes not matching route, using fallback method. Here fit to do some exception handling, such as returning a 404.

Route::fallback(function () {
    return "404 啦";
});

In addition to these types described above, as well as routing groups, routing binding model, access control and other API. But this need to understand other concepts in order to continue. So far the first content routing.

 

Second, the middleware

What is middleware?

wikipedia answers given on: intermediate (English: the Middleware ), also translated middleware, interposer, is software that provides the connection between the system software and application software, in order to communicate between various components of the software, particularly software application for a centralized logic system software, application framework in modern information technology, such as Web services, and other service-oriented architecture used widely.

Simply put, a visit to b, middleware interception in the middle, a and b there is no direct relationship. a visit to intermediate and then visit b.

Middleware here, in fact, and in Java filter / interceptor is one thing, belong to the category of aspect-oriented programming, but not the same name.

Using a middleware approximately three steps.

1. Define Middleware

Suppose we define a middleware age filter.

At the command line php artisan make:middleware CheckAge, the file is automatically created CheckAge.php App / Http / Middleware folder. We can also be created manually.

This file has a file with the same name and class, the class has only one handlemethod. We can write an interceptor logic in it.

? < PHP 
namespace App \ Http \ Middleware; 
use the Closure; 
// definition of middleware, execute the command php artisan make: middleware CheckAge, you can also manually create your own 
class of CheckAge 
{ 
    public  function handle ( $ Request , the Closure $ the Next ) 
    { 
        IF ( $ request -> Age <18 is ) {
             return Response ( 'non-viewable minor' ); 
        } 
        // continue to pass the request to call next, parameters request 
        return  $ Next ( $ request ); 
    } 
}

2. Registration Middleware

In app/Http/Kernel.phpthe $middlewarelist the middleware property.

// add this middleware in the object 
'of CheckAge' => \ App \ Http \ Middleware \ of CheckAge :: class ,

3. Middleware

Create a route, using the middleware method to set the middleware. middleware method accepts variable number of parameters, if desired a plurality of middleware, a plurality of parameters passed into it.

Route::middleware('checkAge')->get('route14/{age}', function ($age) {
    return 'route14';
});

Such access http://homestead.test/api/v1/route14/12would have been blocked, and http://homestead.test/api/v1/route14/22you can get the right resources.

Middleware into effect.

The above three steps are the basic usage of middleware, there are several more advanced usage, but is not commonly used here simply under.

Global registration Middleware

In app/Http/Kernel.phpthe $middlewarelist the middleware property.

Middleware group

Modify $middlewareGroupsthe properties.

Sort Middleware

$middlewarePriority Attribute specifies the middleware priority.

Middleware Parameters

When calling middleware way to "中间件名:参数"way to set parameters. The middleware can handle multi-method accepts a parameter.

 

Third, the controller

The controller is not a new concept.

The nature of the controller, in fact, the callback function route.

The controller can request processing logic associated with the formation of a separate class. The controller is stored in app/Http/Controllersthe directory.

Creating the Controller

In app/Http/Controllera new file in the directory, create classes and methods inside, and simulate some data.

<?php
​
namespace App\Http\Controllers;
​
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
​
class UserController
{
    private $users = [
        ['id' => 1, 'name' => '小明'],
        ['id' => 2, 'name' => '小红'],
        ['id' => 3, 'name' => '小张'],
    ];
​
    public function searchUserById($id)
    {
        $result = "";
        foreach ($this->users as $user) {
            if ($user['id'] = $id) {
                $result = $user;
                break;
            };
        }
        return $result;
    }
}

Using the controller

Create a route, replacing the second parameter to a 命名空间\class名@function名string format.

Route::get('user/{id}', 'UserController@searchUserById');

Request HTTP: //homestead.test/api/v1/user/1 , Xiao Ming will be able to get the data.

The individual behavior of the controller

If you want to define only a single process controller behavior, you can place a in the controller __invokemethod.

For example, in the above example, you want to query the user.

Modify the method name:

public  function __invoke ( $ the above mentioned id ) 
{ 
    // only modify the method name, content unchanged 
    // ... 
}

Modify the route:

Route::get('user/{id}', 'UserController');

Controller Middleware

Except middleware routing methods other than the controller in the constructor specifies more convenient intermediate. But this must inherit Controller class because it provides a middleware approach.

class the UserController the extends the Controller 
{ 
    public  function the __construct () 
    { 
        // indicates that the controller uses chackAge middleware. 
        the this $ -> Middleware ( 'of CheckAge' ); 
    } 
}

In addition to the above, laravel controller as well as resource controller, dependent on advanced usage implantation. But not many applications, temporarily do not speak.

Guess you like

Origin www.cnblogs.com/luzhenqian/p/11432623.html
Recommended