Comprehensive use of laravel 5.5

Time:2021-6-6

Use laravel 5.5 to develop an automatic delivery project, and organize the used open source extension packages and features for subsequent use.

1、 Install ide prompt tool

Laravel ide helper is an extremely useful code prompt and completion tool, which can bring great convenience to code writing.

1. Installation

#If you only want to install in the development environment, add -- dev
composer require barryvdh/laravel-ide-helper

Install doctrine / dbal “please install it. You must use it when annotating fields for the model”

#If you only want to install in the development environment, add -- dev
composer require "doctrine/dbal: ~2.3"

For detailed installation methods, please refer to this blog:Laravel ide helper

Three common commands

  • php artisan ide- helper:generate – Generate comments for facades
  • php artisan ide- helper:models – Generate comments for the data model
  • php artisan ide- helper:meta – Generate phpstorm meta file

2、 Monolog log package

The importance of log is self-evident, whether in the development process or deployed to the production environment, it is often used
along withpsr-3The emergence of the United States, and finally unifiedphpHowever, a good logging system is also very important
monologIt’s the best logging system I’ve ever met. And it’s also used in laravelmonolog

install

composer require monolog/monolog

usage

GitHub address:monolog/monolog

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
// $logger->pushHandler(new StreamHandler(storage_path() . '/logs/spider.log'));

// add records to the log
$log->warning('Foo');
$log->error('Bar');

3、 Bag grabbing tool

GuzzleIs a very powerful PHP simulation HTTP client third-party library, can be installed through composer

GoutteIs a third-party library for parsing HTML documents, which can be installed through composer

install

composer require fabpot/goutte
composer require guzzlehttp/guzzle

Create command

php artisan make:command Spider

Command parameters

//Concurrency is the concurrency number and keywords is the query keyword
protected $signature = 'command:spider {concurrency} {keyWords*}';

actual combat

<?php

namespace App\Console\Commands;

use Goutte\Client as GoutteClient;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Pool;
use Illuminate\Console\Command;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class Spider extends Command
{

    private $totalPageCount;
    private $counter        = 1;
    private $concurrency    = 7;  //  Simultaneous fetching
    private $logger         = null;

    private $urls = [
        'https://www.feixiaohao.com/currencies/bitcoin/', // BTC
        'https://www.feixiaohao.com/currencies/decred/',  // DCR
    ];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = ' test:spider-request '; // Concurrency is the concurrency number and keywords is the query keyword


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'php spider';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //Instantiate a log instance with the parameter channel name
        $logger = new Logger('spider');
        $logger->pushHandler(new StreamHandler(storage_path() . '/logs/spider.log'));
        $this->totalPageCount = count($this->urls);

        $guzzleClent = new GuzzleClient();
        $client = new GoutteClient();

        $client->setClient($guzzleClent);

        $request = function ($total) use ($client){
            foreach ($this->urls as $url){
                yield function () use($client, $url){
                    return $client->request('GET',$url);
                };
            }
        };

        // @DOC http://docs.guzzlephp.org/en/stable/quickstart.html?highlight=pool
        // /Users/kaiyiwang/Code/digcoin/vendor/symfony/dom-crawler/Crawler.php
        $pool = new Pool($guzzleClent,$request($this->totalPageCount), [
            'concurrency' => $this->concurrency,
            'fulfilled' => function ($response, $index) use ($logger){
                $res = $response->html();
                 // print_r($res);

                $logger->info($res);

                $this - > info ("request $index, connection" $this - > URLs [$index]);

                $this->countedAndCheckEnded();
            },
            'rejected' => function ($reason, $index){
                $this->error("rejected" );
                $this->error("rejected reason: " . $reason );
                $this->countedAndCheckEnded();
            },
        ]);

        //Start sending request
        $promise = $pool->promise();
        $promise->wait();

    }

    public function countedAndCheckEnded()
    {
        if ($this->counter < $this->totalPageCount){
            $this->counter++;
            return;
        }
        $this - > info ("request end!");
    }

    //Run command: PHP Artisan test:spider-request
}
> php artisan test:spider-request

Comprehensive use of laravel 5.5

4、 Timed task

Cron is a daemons, it resides in your Linux server, most of the time did not wake up, but every minute it will open its eyes to see whether to run any given task, you use crontab file to communicate with the daemons, in most common settings file can be located in the/etc/crontab, the crontab file might look like this:

0 0 1 * * /home/full-backup
0 0 * * * /home/partial-backup
30 5 10 * * /home/check-subscriptions

1. Add system timing task

It’s very easy to add a timing task in laravel. First, add an artisan timing task in crontab, which is executed every minute.

> crontab -e

//The address of the / home / vagrant / code / digcoin / laravel project on the server
 * * * * * php /home/vagrant/Code/digcoin/artisan schedule:run >> /dev/null 2>&1

Comprehensive use of laravel 5.5

2. Add timing command to the project

stayApp\Console\KernelClassscheduleMethod defines the predetermined command:

protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();

        // php artisan  test:spider-request , called every ten minutes
        $schedule->command('test:spider-request')
            ->everyFifteenMinutes()->withoutOverlapping();
    }

After adding, we can directly use this command to test whether the timing task can be executed

> php /home/vagrant/Code/digcoin/artisan test:spider-request

OK, only two simple steps are needed to add the timing task of laravel.

For more information about laravel’s task scheduling, see this article:Laravel’s task scheduling function task scheduling