Statistics
3
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-09

AuthorBobby Bouwmann & Stefan Bauer

No description

Tags
No tags
Publish Year: 2021
Language: 英文
File Format: PDF
File Size: 888.1 KB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
(This page has no text content)
Table of Contents Foreword 6 .................................................................................................. How the Book Is Structured 7 ......................................................................... Console 8 ..................................................................................................... Console Colors 8 ........................................................................................ Console Progress Bar 11 ............................................................................. Console Tables 20 ...................................................................................... Design Patterns 32 ........................................................................................ Singleton Pattern 32 .................................................................................. Manager Pattern 43 ................................................................................... Null Object Pattern 54 ................................................................................ Models 66 .................................................................................................... Attributes 68 ............................................................................................. Original 71 ................................................................................................ Changes 73 ............................................................................................... Dates 74 ................................................................................................... Touching Relationships 76 .......................................................................... With or Without Relationships 78 ................................................................ Force Fill 79 .............................................................................................. Events on Model Events 81 .........................................................................
Unguard(ed) 82 ......................................................................................... Snippets 84 .................................................................................................. Eloquent & Models 85 ................................................................................ Middleware 98 .......................................................................................... Form Requests 100 .................................................................................... Queues 103 .............................................................................................. Testing 105 ............................................................................................... Laravel Nova 110 ....................................................................................... Helpers 113 .............................................................................................. Collections 119 .......................................................................................... Extras 121 ................................................................................................ Closing 127 .................................................................................................. Credits 128 ...................................................................................................
5
6 Foreword Over the last couple of years, Laravel has quickly become the most popular PHP framework in the ecosystem. With its approachable documentation and excellent learning resources, developers can quickly get started and have their apps up and running in no time. When I started working with Laravel, the documentation was the place to go, whenever I needed to dive deeper into certain parts of the framework. Following known community members on Twitter helped me keep up with the latest tips & tricks around the framework. "Do you know this trick about collections?", "When dealing with date formats, avoid this common error:", "Use this tip to improve your Eloquent queries". Keeping up with the core of the framework is pretty easy to do, thanks to the wide array of available resources. But when you need to learn from best-practices and tips that others had to learn the hard way this is where the Laravel Secrets book shines. The book offers you a lot of tips and best-practices that Bobby and Stefan have learnt themselves while building real-world Laravel applications. It is not just a paraphrased version of the Laravel documentation, but instead, knowledgeable insights from experienced developers. No matter if you are new to the framework, or seemingly know it all - I am sure that you will learn some new tricks to apply in your own codebase from this book. – Marcel Pociot, Jan 2021 CTO at Beyond Code
7 How the Book Is Structured The structure of the book is split into two parts. Chapters and Snippets. Chapters The first part contains chapters that dive into specific subjects and give you in- depth knowledge about the Laravel framework and the specific subject. Subjects vary from everything you need to know about models, the console and design patterns. We picked subjects that we believe are vital to understanding becoming a better Laravel developer. The core concepts we talk about are valuable to understand and will help you improve your thinking and debugging skills. Snippets The second part is a collection of categorized snippets. Each snippet is a small piece of code that improves the developer experience. A snippet can be a feature that is hard to find in the documentation or something that is not documented at all. Most snippets are based on our own experience from working with Laravel for the past years. The snippets can be used as a reference guide when working with specific categories.
8 Console Laravel comes with a bunch of console tools out of the box. Think about running php artisan migrate or php artisan route:list. This chapter will dive into the hidden secrets of the command classes and expose the hidden options available when creating commands. When working with the console, information gets unclear very fast. This is because the console is just text output. It's nothing more than a bunch of characters on your screen. Most of the time your console has a dark background and light characters. Luckily we live in an age where the console is mighty. We can style the console the way we like, use colors, and even use emojis. Although we have all these options, it is still messy. This chapter will teach you how you can use different features to make your console output more beautiful, more readable, and interactive. For this chapter, you need to understand how you can create a command. We won't dive into how we make a command, only how we can improve it and get the most out of it. Console Colors When outputting information on the command line, it quickly get messy. An easy solution may be to add new lines to break up the output, but that doesn’t provide context to the user. Adding some colors to the mix makes messages clear and adds emphasis to the output.
9 Laravel makes it easy to add colors to your output by using one of the default methods like line, warn, error, comment, question, and info. In this case, the line method will be the default color. The warn method will show a yellow color. The error will display white text on a red background. The question method displays black text on a cyan background. Finally, the info method will display text with a green color. // Default color $this->line('This is a line'); // Yellow collor $this->warn('This is a warning'); $this->comment('This is a comment'); // White text on red background $this->error('This is an error'); // Black text on cyan background $this->question('This is a question'); // Green color $this->info('This is some info'); Notice: Console colors are defined by the terminal itself. Green for example could be colored differently to what you expect, based on the settings in your terminal.
10 More Colors Laravel already offers some cool options out of the box, but we can even take it a step further. When writing to the command line, we can define the foreground color, and the output's background color. Let's see how we can do that: $this->line('<bg=black> My awesome message </>'); $this->line('<fg=green> My awesome message </>'); $this->line('<bg=red;fg=yellow> My awesome message </>'); $this->line('<bg=red;fg=yellow> My awesome message </>'); The abbrevation bg stands for background, while fg stands for foreground (the text color). Notice: Keep in mind that you might need to add extra spaces around the text to make it more readable because of the bold background color. Next to that, we can add more options like bold text to emphasize the output. $this->line("<options=bold;fg=red> MY AWESOME MESSAGE </>"); $this->line("<options=bold;fg=red> MY AWESOME MESSAGE </>"); $this->line("<options=underscore;bg=cyan;fg=blue> MY MESSAGE </>"); We may pick one of the following colors: black, red, green, yellow, blue, magenta, cyan, white, default and we may pick one of the following options bold, underscore, blink, reverse, and conceal for the font style. The reverse option can be handy to swap the background and foreground colors.
11 Console Progress Bar Laravel offers this neat feature to show a progress bar when running a command on the console. The progress bar in Laravel is based on the Symfony Progress Bar Component. Laravel itself is currently not using this feature in the framework. You probably have seen such a progress bar when using npm or yarn. $ npm install (█████████░░░░░░░░░) preinstall:secrets: info lifecycle @~preinstall: @ $ yarn yarn install v1.17.3 info No lockfile found. [1/4] Resolving packages... [2/4] Fetching packages... [#########################################################------] 771/923 In the next part, we will be building a simple CSV importer for users. This small tool will display the numbers of users we have imported and show us the current progress. Eventually, we will end up with output like this: $ php artisan secrets:import-users users.csv 4/4 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
12 Below you can find the code of the command-line tool. class ImportUsers extends Command { protected $signature = 'secrets:import-users {file : A CSV with the list of users}'; protected $description = 'Import users from a CSV file.'; public function handle() { $lines = $this->parseCsvFile($this->argument('file')); $progressBar = $this->output->createProgressBar(); $progressBar->start(); $lines->each(function ($line) use ($progressBar) { $this->convertLineToUser($line); $progressBar->advance(); }); $progressBar->finish(); } // class specific methods } If we dive into the code behind the user importer, we can see a few important things here. First, we have a parseCsvFile method, which transforms the CSV file into a collection. This way, we can easily loop over the results but also get the current count. We could have used a simple array here as well. However, the collection gives us different methods, which makes it more readable.
13 Next, we create a new progress bar in the output of our command. This means that we create a new ProgressBar instance and pass the number of items we expect to process. Then we need to start the progress bar itself. It will set the current time on the progress bar, and it will set the steps to 0 as well. After that, we can start looping over your data and perform your actions. In this case, convertLineToUser is converting a line's data to a new user in the database. The final step in our loop is to advance the progress bar. Whenever we call $progressBar->advance(), we will increase the progress bar's steps and output the current state. Finally, we call finish on the progress bar to make sure it shows that we are 100% there and close the progress bar. Override Output In our case, we have four users. However, you only see one line of output in the console. This means the output will be overwritten on each step. Whenever we advance a step, the output will be overridden by default. So it redraws the output on the same line. $ php artisan secrets:import-users users.csv 4/4 [============================] 100%
14 We can turn this off. This way, we will be drawing 5 times to the console. We have the start method first to show that we have zero progress. Then, whenever we complete the first one, we add 25% to the bar and display that. So it will only add something to the output whenever it's finished in the loop. If we want to do this, we can simply turn it off by doing the following: $progressBar = $this->output->createProgressBar($lines->count()); $progressBar->setOverwrite(false); The output will then look like this: $ php artisan secrets:import-users users.csv 0/4 [> ] 0% 1/4 [=======> ] 25% 2/4 [==============> ] 50% 3/4 [=====================> ] 75% 4/4 [============================] 100% Notice: When overwrite is enabled you would only see one line in the above example. With overwrite disabled you get an output line for each item.
15 Custom Messages In some cases, you want to show how much time is remaining for processing your data. This is mostly useful whenever you have to import a lot of data, or a slow processing bit of data. Think about inserting into a lot of tables or using APIs when processing your data. Also, just displaying additional data can be useful. By default, the message written to the console looks like this: ' %current%/%max% [%bar%] %percent:3s%%' The %current% variable displays the current step, or the current count of items we already have processed. The %max% variable means the maximum number of things we will be processing. You can override the max number by calling setMaxSteps manually on the progress bar. In our case, this number is set by using $lines->count() when creating the ProgressBar. Next up is the %bar variable, which displays the actual loading bar. The final parameter indicates a percentage based on the max number of steps divided by the current step. Because :3s is appended to the percent variable, the result will always be shown as three characters. This makes sure the percentages line out to the right. We can override this message and provide our own format with our custom data. To do that, we will first need to set the custom message and assign it to the progress bar. After that, it's just business as usual, and we loop over the data and set a message per action.
16 ProgressBar::setFormatDefinition('custom', ' %current%/%max% [%bar%] %message%'); $progressBar = $this->output->createProgressBar($lines->count()); $progressBar->setFormat('custom'); $progressBar->setMessage('Starting...'); $progressBar->start(); $lines->each(function ($line) use ($progressBar) { $this->convertLineToUser($line); $message = sprintf( '%d seconds remaining', $this->calculateRemainingTime($progressBar) ); $progressBar->setMessage($message); $progressBar->advance(); }); $progressBar->setMessage('Finished!'); $progressBar->finish(); With this custom message, we get an output like this: 0/4 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░] Starting... 1/4 [▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░] 8 seconds remaining 2/4 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░░░] 5 seconds remaining 3/4 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░] 2 seconds remaining 4/4 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] Finished!
17 As you can see, there is already a progress bar that indicates how much percentage is completed. However, that doesn't say anything about the remaining time. The messages provide extra value here by showing an estimation of the remaining time together with the progress bar. Custom Progress Bar You have already seen how the progress bar looks like. In most cases this is perfectly fine. By default, the progress bar looks like this: 4/4 [============================] 100% To enjoy looking at the progress bar when waiting, we can spice it up a bit. In this case, we don't have to change much to make this work. We only need to set the characters we want to see: $progressBar = $this->output->createProgressBar($lines->count()); $progressBar->setBarCharacter('='); $progressBar->setProgressCharacter('>'); $progressBar->setEmptyBarCharacter(' '); This will then result in the following output: 0/2 [> ] 0% 1/2 [==============> ] 50% 2/2 [============================] 100%
18 We can even take this a step further and use emojis in here. To do this, we need a Spatie package to make this easy for us. So if we run composer require spatie/emoji, we can start using these emojis in our output: use Spatie\Emoji\Emoji; $progressBar->setBarCharacter('='); $progressBar->setProgressCharacter(Emoji::hourglassNotDone()); $progressBar->setEmptyBarCharacter(' '); This will then result in the following output: 2/4 [============== ] 50% Pretty neat, right?!
19 withProgressBar Since Laravel 8, there is a convenient method to generate a progress bar called withProgressBar. This method performs the same action as creating a progress bar yourself and advancing it manually. You now have one callback that you can use to perform your action on each item in the array. The method will make sure the progress bar advances to the next step and calls finish after the last time. public function handle() { $lines = $this->parseCsvFile($this->argument('file')); $this->withProgressBar($lines, function ($line) { $this->convertLineToUser($line); }); } The withProgressBar method is handy and fast but doesn't allow for any customizations in the output. Why Customize the Progress Bar? You have played around with the console commands, and the progress bar that is the default in Laravel. The default bar is sufficient in most cases, so why would you optimize this? It mostly comes down to developer experience. If you are like us, you will spend an insane amount of time on the command line. It's also nice to see some colors and better readable output than always the default output. Especially when you have a long-running process. A customized progress bar can make this even more enjoyable and gives you more info while waiting!
20 Console Tables Outputting a large amount of data to the command line can quickly become a hell. Luckily there are tables that can display your data in a more readable way. The tables in Laravel are based on the Symfony Table Component. For example, if we look at the php artisan route:list command, we always get a table back as a response with our routes in there. It is the default layout of a table for the console component in Laravel. $ php artisan route:list +--------+----------+----------+------+---------+--------------+ | Domain | Method | URI | Name | Action | Middleware | +--------+----------+----------+------+---------+--------------+ | | GET|HEAD | / | | Closure | web | | | GET|HEAD | api/user | | Closure | api,auth:api | +--------+----------+----------+------+---------+--------------+