Laravel Framework One: Principle Mechanism Chapter

Source: Internet
Author: User
Tags closure event listener php framework riak
Laravel, as a popular PHP framework in China and abroad, has its own features and elegant style.

a . Request Cycle

  Laravel adopts a single entry mode, and all the request portals applied are public/index.php files.Register class file Auto Loader: Laravel through composer for dependency management, and registered in bootstrap/autoload.php composer Auto Loader (PSR-4), the namespace of the application class will be mapped to the class file actual path. Developers are no longer required to manually import various class files and are imported by the loader itself. Therefore, Laravel allows classes defined in your application to be freely placed in any directory that the composer Auto Loader can automatically load, but most of the time it is recommended to be placed in the app directory or in a subdirectory of the app.Create a service container: Obtain the Laravel application instance from the bootstrap/app.php file $app (service container)creating the Http/console kernel: Incoming requests are sent to the HTTP kernel or the console kernel for processing, and the HTTP kernel inherits from the Illuminate\foundation\http\kernel class. It defines a bootstrappers array in which the classes in the array are executed before the request is actually executed, configured with error handling, logging, detecting the application environment, and other work that needs to be done before the request is processed; The HTTP kernel also defines an HTTP Middleware list, all requests must handle HTTP session read and write through these middleware before processing, judge whether the application is in maintenance mode, verify CSRF token, etc.Load service provider to container: One of the most important actions in the kernel boot boot process is to load the service provider into your application, and the service provider is responsible for booting all the various components of the startup framework, such as databases, queues, validators, and routing components. Because these components boot and configure the various capabilities of the framework, the service provider is the most important part of the entire Laravel startup process, and all service providers are configured in the providers array in the config/app.php file. First, all providers ' register methods are invoked, and once all providers are registered, the boot method will be calledDistribution Requests: Once the application completes the boot and all service providers are registered, Request will be handed over to the route for distribution. Routing assigns a distribution request to a routing or controller while running the middleware specified by the route

two. Service containers and service providers

The service container is a powerful tool for Laravel management dependencies and running dependency injection, where the container is accessed by $this->app , outside the class, through the $app ; The service provider is Laravel The center of the application boot boot is related to the service provider itself, event listeners, routing, and Middleware startup operations. The routes registered in the application are loaded by Routeserviceprovider instances, the event listeners are registered in the Eventserviceprovider class, and the middleware is called routing middleware in app/http/ Kernel.php the class file, which is bound to the route when invoked. In the newly created application, the method implementation in the Appserviceprovider file is empty, and this provider is the best place for you to add the application-specific boot and service, and of course, for large applications you may want to create several service providers, each with a finer granularity of guidance. The service provider registers in the providers array in the config/app.php configuration file

<?php

namespace App\providers;

Use riak\connection;
Use Illuminate\support\serviceprovider;

Class Riakserviceprovider extends serviceprovider
{
    /**
     * Register bindings in Container
     * *
     @return void
    / Public Function Register ()
    {
        $this->app->singleton (connection::class, function ($app) {
            return New Connection (config (' Riak '));}

 

three. Dependency Injection

There are two types of laravel implementation Dependency Injection: Automatic injection and active registration. Automatic injection is realized by the service container automatically by the parameter type hint, and the active registration requires the developer to implement by binding mechanism, namely binding service provider or class (reference: Http://d.laravel-china.org/docs/5.4/container). Binding service Provider or class: the implementation of dependency injection can be very flexible in this way

Use Illuminate\support\facades\storage;
Use App\http\controllers\photocontroller;
Use App\http\controllers\videocontroller;
Use Illuminate\contracts\filesystem\filesystem;

$this->app->when (Photocontroller::class)
          ->needs (filesystem::class)
          ->give (function () { Return
              Storage::d ISK (' local ');

$this->app->when (Videocontroller::class)
          ->needs (filesystem::class)
          ->give (function () { Return
              Storage::d ISK (' S3 ');
          };
parameter type declaration: By giving a hint to the constructor parameter type of class, the method parameter type of the class, the parameter type of the closure
<?php

namespace App\http\controllers;

Use App\users\repository as userrepository;

Class Usercontroller extends Controller
{
    /**
     * User Repository instance.
     * *
    protected $users;

    /**
     * Controller construction method. * *
     @param  userrepository  $users
     * @return void
     *
    /Public Function __construct ( Userrepository $users)
    {
        $this->users = $users;
    }

    /**
     * Store a new user.
     *
     @param  request  $request
     * @return Response/public
    function Store (request $request)
    {
        $name = $request->input (' name ');

        //
    }
}
Routing parameter dependencies:The following example uses the Illuminate\http\request type hint and also gets the route parameter ID
Your route may be defined in this way:
Route::p ut (' User/{id} ', ' Usercontroller@update ');

The controller's reliance on routing parameter IDs may be achieved by:
<?php

namespace app\http\controllers;

Use Illuminate\http\request;

Class Usercontroller extends Controller
{
    /**
     * Updates the specified user.
     *
     @param  Request  $request
     * @param  string  $id
     * @return Response
     * /Public
    function Update (Request $request, $id)
    {
        //
    }
}

four. Artisan Console

Laravel uses PHP's CLI to build a powerful console tool Artisan,artisan can almost create any template class you want and manage your application, playing an extremely important role in development and operational management. Artisan is an indispensable tool for laravel development. Run under the Laravel root directory: PHP artisan list to view all command lists. Using good artisan can greatly simplify development work and reduce the likelihood of errors, and you can write your own commands. The following are some of the more commonly used commands: Enable maintenance mode : PHP artisan down--message= ' upgrading Database '--retry=60 shutdown maintenance Mode : PHP artisan Up Generation routing cache : PHP artisan route:cache Clear Routing cache : PHP artisan route:clear Database migration Migrations: PHP Artisan make:migration create_users_table--create=users Create a resource controller : PHP artisan Make:controller --resource--model=photo Create model and Migration : PHP artisan Make:model user-m

Five. form Verification Mechanism

  Form validation is indispensable in web development, and it is important to be a standard part of each web framework. Laravel form validation has a standard and large set of rules that can be validated by rule calls, and multiple rule combinations are called with the "|" Symbolic connections, which are automatically rolled back once the validation fails and automatically bind the view.

In the following example, append the bail rule to the title property and stop the validation immediately after the first validation of the required failure; "." Grammatical symbols usually represent nested inclusion relationships in Laravel, which is also common in other language or framework syntax

$this->validate ($request, [
    ' title ' => ' bail|required|unique:posts|max:255 ', '
    author.name ' => ') Required ',
    ' author.description ' => ' required ',
]);

Laravel validation rules refer to the http://d.laravel-china.org/docs/5.4/validation# validation rules that are available and, in addition, the following extension rules can be used in Laravel development: Custom Formrequest ( Must inherit from Illuminate\foundation\http\formrequest) Validator::make () Manually create Validator instance create Validator instance verify hook conditionally increase rule array validation Custom validation Rules

Six. Event mechanisms

The Laravel event mechanism is a good decoupling method because an event can have multiple listeners that are not dependent on each other. Event classes are usually saved in the App/events directory, and their listener class (Listener) classes are saved under the App/listeners directory, and they are automatically created when the Artisan command is used to generate events and listeners. registering events and listeners : Eventserviceprovider's Listen property array is used to register the event (key) to the corresponding listener (value), and then run the PHP artisan event: Generate will automatically generate the event (class) templates and listener templates that are registered in Eventserviceprovider, and then modify them to implement the full event and listener definitions; In addition, you can also use the Eventserviceprovider class The boot method implements the definition event (Class)by registering a closure event: the event (Class) is a container containing information about the event and does not contain other logic

1 <?php
 2 
 3 namespace app\events;
 4 
 5 use App\order;
 6 use Illuminate\queue\serializesmodels;
 7 
 8 Class ordershipped
 9 {
use     serializesmodels;
A 
public     $order;     /**      Create an event instance.
*      @param order $order *      @return void
*/20 Public     function __construct (order $order)     {         $this->order = $order;
24}
Defining listeners: The event listener accepted the event instance as a parameter in the handle method
1 <?php
 2 
 3 namespace app\listeners;
 4 
 5 use app\events\ordershipped;
 6 
 7 class Sendshipmentnotification
 8 {
 9     /**      * Create event listeners.
*      @return void
/public     function __construct ()
15
/** *
22 of processing events (*)      * @param  ordershipped  $event      * @return void * * Public     function handle ( ordershipped $event)         //Use $event->order to access order ...     }
29}
Stop Event Propagation: Returns false in the listener's handle method to stop an event from propagating to another listener Triggering Events: Invoking the event helper function triggers an incident that is distributed to all of its registered listeners
1 <?php
 2 
 3 namespace app\http\controllers;
 4 
 5 use App\order;
 6 use app\events\ordershipped;
 7 use App\http\controllers\controller;
 8 
 9 class Ordercontroller extends Controller     /**      will deliver the order shipped over.
*      @param  int  $orderId      * @return Response      * * The public     function ship ($orderId)     {         $order = Order::findorfail ($orderId);         //order shipping Logic
...         Event (New ordershipped ($order));
25}
Queue Event Listener: If you need to implement some time-consuming tasks in your listener, such as sending a message or making an HTTP request, it is useful to put it in the queue for processing. When using a queuing listener, you must configure the queue in the server or local environment and open a queue listener, and add the Shouldqueue interface to your listener class; If you want to customize the connection and name of the queue, you can define $connection and $queue properties in the Listener class If the queue listener task executes more times than the maximum number of attempts defined in the work queue, the listener's failed method is automatically invoked
1 <?php
 2 
 3 namespace app\listeners;
 4 
 5 use app\events\ordershipped;
 6 use Illuminate\contracts\queue\shouldqueue;
 7 
 8 class Sendshipmentnotification implements Shouldqueue
 9 {     /**      The connection name used by the queue task.      @var string|null public     $connection = ' SQS ';     /**      * Queue name used by the queue task.      * *      @var string|null public     $queue = ' listeners ';
Public     function failed (ordershipped $event, $exception)     {
27     }       
28}

Event subscribers : Event subscribers allow you to define multiple event handlers in a single class, and you should define a subscribe method that takes an instance of an event dispatcher, registers the event listener by invoking the Listen method of the event dispatcher, and then Register subscribers in the $subscribe properties of the Eventserviceprovider class

 1 <?php 2 3 namespace App\listeners;
 4 5 class Usereventsubscriber 6 {7/** 8 * Handles user logon events.
9/A Public function Onuserlogin ($event) {} 11 12/** 13 * Handles user logoff events.
The Public Function onuserlogout ($event) {} 16 17/** 18 * Registers listeners with subscribers.     * * @param illuminate\events\dispatcher $events/Public Function Subscribe ($events) 23 {$events->listen (

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.