Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Laravel8 locates Numb1 problems by disabling latency

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is to share with you about how Laravel8 locates Number1 problems by disabling latency. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

In the next version of Laravel 8, you can disable delayed loading completely, resulting in an exception:

Prevent Nation1 problems? @ themsaid's recent contribution to the framework allows you to completely disable delayed loading (which will throw an exception).

It can only be disabled in a non-production environment, so that production does not collapse when something goes wrong in a process!

Release next week! Pic.twitter.com/5Q9YpCLRze

-Taylor Otwell (@ taylorotwell) May 19, 2021

Preventing delayed loading in development can help you catch Numb1 errors early in the development process. The Laravel ecosystem has a variety of tools to identify Number1 queries. However, this approach puts the problem at the front and center by throwing an exception.

Demo

Let's take a quick look at this feature by rotating the development version of the 8.x branch of the framework, because it hasn't been released at the time of this writing. Once released, you will have this feature without having to switch to the latest 8.x branch.

Installation

First, create a new application:

Laravel new strict-lazy-demo

Next, we will update the laravel/framework version in composer.json to ensure that we have this feature by adjusting the version to 8.x-dev (if you try this feature before the next version):

{"require": {"laravel/framework": "8.x-dev"}}

Next, run composer update to make sure you get the latest version of the code for this branch:

Composer update laravel/framework

At this point, you should set the preferred database. I like to run the local MySQL instance with the default value of Laravel, even with the root user instead of the password. I find it convenient to use the default .env value locally and start quickly without any configuration.

Mysql-uroot-e "create database strict_lazy_demo"

After you configure the selected database, make sure that you can migrate:

Php artisan migrate:freshDemo Data

We will demonstrate this functionality by creating a Post model and defining an one-to-many relationship from the User model. We will first create the Post model and the accompanying files:

# create a model php artisan make:model-mf Post using migration and factory

First, let's define the Post migration and factory configuration:

/ / your file name will vary depending on when the file was created. / / 2021_05_21_000013_create_posts_table.phpSchema::create ('posts', function (Blueprint $table) {$table- > id (); $table- > foreignIdFor (\ App\ Models\ User::class); $table- > string (' title'); $table- > longText ('body'); $table- > timestamps ();})

Next, define the PostFactory definition method according to the above schema:

/ * Define the model's default state. * * @ return array * / public function definition () {return ['user_id' = >\ App\ Models\ User::factory (),' title' = > $this- > faker- > sentence (), 'body' = > implode ("\ n\ n", $this- > faker- > paragraphs (rand (2)),];}

Finally, open the DatabaseSeeder file and add the following to the run () method:

/ * database filler. * * @ return void * / public function run () {\ App\ Models\ User::factory ()-> has (\ App\ Models\ Post::factory ()-> count (3)-> create ();} correlate the model and prevent delayed loading

Now that we have created the migration file, fill file, and model, we are ready to associate User with the Post model to demonstrate this feature. Add the following method to the User model to give the user an association with Posts:

/ / app/Models/User.php/** * @ return\ Illuminate\ Database\ Eloquent\ Relations\ HasMany * / public function posts () {return $this- > hasMany (Post::class);}

With these, we can migrate and populate the database:

Php artisan migrate:fresh-seed

If all goes well, we will see the following in the console:

Now we can use tinker to check our populated data and relationships:

Php artisan tinker > > $user = User::first () = > App\ Models\ User {# 4091 id: 1, name: "Nedra Hayes", email: "bruen.marc@example.com", email_verified_at: "2021-05-21 00:35:59", created_at: "2021-05-21 00:35:59", updated_at: "2021-05-21 00:35:59" } > $user- > posts= > Illuminate\ Database\ Eloquent\ Collection {# 3686 all: [App\ Models\ Post {# 3369 id: 1.

The $user- > posts attribute actually invokes the database, so it is "lazy" but not optimized. Delayed loading is convenient, but in the long run it can impose a heavy performance burden.

Disable delayed loading

Now that we have set up the model, we can disable delayed loading in the application. You may only want to disable it in a non-production environment, which is easy to achieve! Open the AppServiceProvider class and add the following to the boot () method:

/ / app/Providers/AppServiceProvider.phppublic function boot () {Model::preventLazyLoading (! App ()-> isProduction ();}

When you run php artisan tinker again, you should receive a delayed load violation exception:

Php artisan tinker > > $user =\ App\ Models\ User::first () = > App\ Models\ User {# 3685 id: 1, name: "Nedra Hayes", email: "bruen.marc@example.com", email_verified_at: "2021-05-21 00:35:59", # password: "$2y$10 $92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", # remember_token: "jHSxFGKOdw" Created_at: "2021-05-21 00:35:59", updated_at: "2021-05-21 00:35:59",} > $user- > postsIlluminate\ Database\ LazyLoadingViolationException with message'Attempted to lazy load [posts] on model [App\ Models\ User] but lazy loading is disabled.'

If you want to observe what happens when lazy loading is used in the view, modify the default route as follows:

Route::get ('/', function () {return view ('welcome', [' user' = >\ App\ Models\ User::first ()];})

Next, add the following somewhere in the welcome.blade.php file:

Posts@foreach ($user- > posts as $post) {{$post- > title}}

{{$post- > body}}

@ endforeach

If you load your application through Valet or artisan serve, you should have an exception.

Although you encounter exceptions during development, code that accidentally deploys and triggers delayed loading will continue to work as long as you set up the environment check correctly in the service provider.

Thank you for reading! This is the end of the article on "how Laravel8 locates Number1 problems by disabling latency". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report