日志-2019年10月

2019-10

2019-10-8 周二

以下两种写法可以等效

return isset($modifiedNames[$this->modified]) ? $modifiedNames[$this->modified] : $this->modified;
return $modifiedNames[$this->modified] ?? $this->modified;

2019-10-9 周三

Kernel

执行

php artisan test

2019-10-10 周四

添加索引

$table->index(['retrieved_at', 'approved_at'], 'index_idx');
$table->index(['deleted_at', 'res_type_id'], 'idx_deletedat_restypeid');

2019-10-11 周五

小心使用 artisan 命令,防止清空数据库

php artisan migrate:fresh
php artisan migrate:fresh --seed

修改完配置文件需要及时执行

php artisan config:clear

今天误把集成环境数据库清空了,在 .ENV 文件中修改过后,一定要刷新设置

2019-10-12 周六

添加了定时任务的监控后出现了同一任务多次报错发送邮件的问题,现在将错误的文件名放到 Redis 中记录,过期时间为 1天

// 限制同一文件一天内只发送一次邮件
if (!Cache::has('exception:'.$e->getFile())) {
    dispatch(new SendEmail('email.exception', $data, $emailAddresses, $subject));

    $expiresAt = Carbon::now()->addDay(1); // 键值过期时间
    Cache::put('exception:'.$e->getFile(), 'exception', $expiresAt);
}

2019-10-14 周一

因为 Horizon 无法在 Windows 中安装,所以安装新的依赖时需要加上 --ignore-platform-reqs

composer install --ignore-platform-reqs

在数据库中存储为 decimal 类型的数据,记录其历史时需要标记为 float 才行:


namespace App\Models\Records;
class Deposit extends BaseRecords
{
public function recordMappings(): array
{
return [
'will_refund_deposit' => $this->mapping('备退押金', 'float'),
'refunded_deposit' => $this->mapping('已退押金', 'float'),
'deposit_status' => $this->mapping('押金状态', 'integer')->customDisplayData($this->depositStatusDisplay()),
'deposit_refund_type' => $this->mapping('退回方式', 'integer')->customDisplayData($this->depositRefundTypeDisplay()),
'deposit_refund_payment_subject' => $this->mapping('出款主体', 'integer')->customDisplayData($this->depositRefundPaymentSubjectDisplay()),
'deposit_refund_user_name' => $this->mapping('用户名称', 'string'),
'deposit_remark' => $this->mapping('备注', 'string'),
];
}
protected function depositStatusDisplay()
{
return function ($value) {
$depositStatuses = [
0 => '不退押金',
1 => '未处理',
2 => '已退押金',
3 => '等待确认',
];
return $depositStatuses[$value] ?? $value;
};
}
protected function depositRefundTypeDisplay()
{
return function ($value) {
$depositRefundTypes = [
1 => '现金',
2 => '银行卡',
3 => '微信',
4 => '支付宝',
5 => '对公转账',
];
return $depositRefundTypes[$value] ?? $value;
};
}
}

2019-10-15 周二

引入 iseed

composer require orangehill/iseed --ignore-platform-reqs

2019-10-16 周三

iseed 的使用方法

php artisan iseed [{TABLE NAME},{TABLE NAME},{TABLE NAME}] 

指定输出的种子文件的前缀名:--classnameprefix=Customized
覆盖现有的种子文件名:--force
清除app/database/seeds/DatabaseSeeder.php--clean
指定数据库连接名称:--database=mysql2
指定生成的种子数的最大条目数:--max=10
指定插入查询的数据块大小:--chunksize=100
指定最大条目数的排列依据:--orderby=id
指定最大条目数的排列顺序:--direction=desc
指定需要排除的列:--exclude=id,created_at,updated_at
指定在播种之前需要触发的事件名称: --prerun=someUserEvent,someGroupEvent
指定在播种之后需要触发的事件名称:--postrun=someUserEvent,someGroupEvent
将种子生成为非索引数组:--noindex

php artisan iseed field_order_item_deductions,field_order_item_relations,field_order_item_scopes,field_order_item_shifts,field_order_items,field_order_receivable_shifts,field_order_receivables,field_order_receivables,field_orders --max=10 --orderby=id --direction=desc
php artisan iseed invoice_infos,invoice_orders,invoice_title_infos,invoices --max=10 --orderby=id --direction=desc
php artisan iseed task_attachments,task_records,task_relations,task_types,tasks --max=10 --orderby=id --direction=desc

2019-10-17 周四

表名称可以指定

protected $table = 'consignee_addresses';

2019-10-18 周五

多个数据库连接指定

ENV 文件中:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database
DB_USERNAME=root
DB_PASSWORD=
DB_HOST_CENTER=127.0.0.1
DB_PORT_CENTER=3306
DB_DATABASE_CENTER=database
DB_USERNAME_CENTER=root
DB_PASSWORD_CENTER=

config 文件中

'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'data_center' => [
'driver' => 'mysql',
'host' => env('DB_HOST_CENTER', 'localhost'),
'port' => env('DB_PORT_CENTER', '3306'),
'database' => env('DB_DATABASE_CENTER', 'forge'),
'username' => env('DB_USERNAME_CENTER', 'forge'),
'password' => env('DB_PASSWORD_CENTER', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],

模型中指定 $connection 即可:

class UserModel extends Model
{
  // 指定数据库'dadtabase_center'中的users表
protected $connection = 'data_center';
protected $table = "users";
}

2019-10-21 周一

Aritisan 激励命令

执行以下命令会随机生成一句激励的名人名言

php artisan inspire

实现方法如下:
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Inspiring.php


namespace Illuminate\Foundation;
use Illuminate\Support\Collection;
class Inspiring
{
/**
* Get an inspiring quote.
* Taylor & Dayle made this commit from Jungfraujoch. (11,333 ft.)
* May McGinnis always control the board. #LaraconUS2015
* RIP Charlie - Feb 6, 2018
* @return string
*/
public static function quote()
{
return Collection::make([
'When there is no desire, all things are at peace. - Laozi',
'Simplicity is the ultimate sophistication. - Leonardo da Vinci',
'Simplicity is the essence of happiness. - Cedric Bledsoe',
'Smile, breathe, and go slowly. - Thich Nhat Hanh',
'Simplicity is an acquired taste. - Katharine Gerould',
'Well begun is half done. - Aristotle',
'He who is contented is rich. - Laozi',
'Very little is needed to make a happy life. - Marcus Antoninus',
'It is quality rather than quantity that matters. - Lucius Annaeus Seneca',
'Genius is one percent inspiration and ninety-nine percent perspiration. - Thomas Edison',
'Computer science is no more about computers than astronomy is about telescopes. - Edsger Dijkstra',
'It always seems impossible until it is done. - Nelson Mandela',
'Act only according to that maxim whereby you can, at the same time, will that it should become a universal law. - Immanuel Kant',
])->random();
}
}

2019-10-22 周二

IIS 服务器配置 Laravel ,在 public 目录下添加 web.config 文件:


<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTPS}" pattern="OFF" />
<add input="{HTTPS_HOST}" pattern="^(localhost)" negate="true" />
conditions>
<action type="Redirect" url="https://{HTTP_HOST}:443/{R:1}" redirectType="Found" />
rule>
<rule name="Rule URL" stopProcessing="true">
<match url="^(.*)/$" ignoreCase="false" />
<action type="Redirect" redirectType="Permanent" url="/{R:1}" />
rule>
<rule name="Rule FILE" stopProcessing="true">
<match url="^" ignoreCase="false" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
conditions>
<action type="Rewrite" url="index.php" />
rule>
rules>
rewrite>
system.webServer>
configuration>

PHP中开启的插件(这里列出的可能不全):

extension=php_mysqli.dll
extension=php_mbstring.dll
extension=php_gd2.dll
extension=php_gettext.dll
extension=php_curl.dll
extension=php_exif.dll
extension=php_xmlrpc.dll
extension=php_openssl.dll
extension=php_soap.dll
extension=php_pdo_mysql.dll
extension=php_pdo_sqlite.dll
extension=php_imap.dll
extension=php_tidy.dll
extension=php_fileinfo.dll
extension=php_redis.dll

执行 composer install

2019-10-23 周三

Composer 指定镜像

"repositories": {
"packagist": {
"type": "composer",
"url": "https://mirrors.aliyun.com/composer/"
}
}
composer require laravel/ui

2019-10-24 周四

NPM 相关

npm install --save-dev cross-env  --no-bin-links
npm install webpack --save (不需要)
"dev": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch-poll": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --watch-poll --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"hot": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"production": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
npm install --no-bin-links
npm run prod

2019-10-25 周五

Laravel 相关权限包安装:

composer require spatie/laravel-permission

基本操作

// 向用户添加权限
$user->givePermissionTo('edit articles');
// 通过角色添加权限
$user->assignRole('writer');
// 给予权限
$role->givePermissionTo('edit articles');
// 判断是否有权限
$user->can('edit articles');
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"

Dingo API 安装

composer require dingo/api
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

2019-10-26 周六

开启本地自带的服务:

php artisan serve

2019-10-28 周一

正则表达式

8-16位数字+字母

$a = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/';
$str = "test123456";
return preg_match($a, $str);

2019-10-29 周二

检查用户密码是否匹配:

Hash::check($old_password, $user->password);

生成一个 crypt 密码:

Hash::make($password);

2019-10-30 周三

新建项目

在项目中,你可以存放文件(存储库),计划工作(问题)和发布文档(维基)等等

对于空白项目,从模板或在导入时,都启用了所有功能,但是之后可以在项目设置中将其禁用。

有关其他页面模板以及如何安装它们的信息,可以在页面入门指南中找到。

提示: 你还可以从命令行创建项目。 显示命令


2019-10-31 周四

匿名函数的使用

如下:


$array = array(1, 2, 3, 4);
// array_walk 使用用户自定义函数对数组中的每个元素做回调处理
array_walk($array, function($value) { // 输出1234
echo $value;
});
?>

若要在父作用域中继承变量则使用 use 关键词来继承作用域外的变量,例如:


function getCounter() {
$i = 0;
return function() use ($i) {
Echo ++$i;
};
}
$counter = getCounter();
$counter(); // 输出1
$counter(); // 输出1
?>

若要改变上层变量的值,则需要通过引用的方式传递 (&$i)