開發錯誤集錦

emoji

utf8 編碼問題 https://laravel-china.org/top...php

function nickname_encode($s){
        $chars = preg_split('//u', $s, null, PREG_SPLIT_NO_EMPTY);
        foreach ($chars as &$c) {
            if (strlen($c) > 3 || $c === "%"){
                $c = urlencode($c);
            }
        }

        return implode($chars);
    }
解碼直接用urldecode就好了。

strtotime

var_dump(date("Y-m-d", strtotime("2017-06-31")));
//輸出2017-07-01
var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2017-03-31"))));
//輸出2017-03-03
var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2017-08-31"))));
//輸出2017-10-01
var_dump(date("Y-m-d", strtotime("next month", strtotime("2017-01-31"))));
//輸出2017-03-03
var_dump(date("Y-m-d", strtotime("last month", strtotime("2017-03-31"))));
//輸出2017-03-03

var_dump(date("Y-m-d", strtotime("last day of -1 month", strtotime("2017-03-31"))));
//輸出2017-02-28
var_dump(date("Y-m-d", strtotime("first day of +1 month", strtotime("2017-08-31"))));
////輸出2017-09-01
var_dump(date("Y-m-d", strtotime("first day of next month", strtotime("2017-01-31"))));
////輸出2017-02-01
var_dump(date("Y-m-d", strtotime("last day of last month", strtotime("2017-03-31"))));
////輸出2017-02-28

須要得到多少天以前 $day 

mktime(0, 0, 0, date("m", $startTime), date("d", $startTime) - $day, date("Y", $startTime));

 這個坑在carbon中同樣的有. 好比:Carbon::now()->subMonth(1)->startOfMonth() 同樣的會出現上面說的問題. 你必須這樣寫:Carbon::now()->startOfMonth()->subMonth(1)
 Carbon::now()->subMonthNoOverflow(1)->startOfMonth()
https://laravel-china.org/articles/17317

$i = 12;

while($i >= 1) {
    echo date('Y-m', strtotime('-' . $i . ' month', strtotime('2018-8'))) . "\n";
    $i--;
}

https://laravel-china.org/art...
解決方法html

??

運算符可 用於判斷$a變量不存在的狀況(也可用於數組),而使用三元運算符判斷一個未定義的變量,PHP會拋出異常。也正是由於這樣,用??判斷一個賦值爲0的變量的時候結果是不同的。https://laravel-china.org/articles/17304?#reply64712
$a=0;
$c=1;
$b=$a??$c;
echo 'a:'.$a.',b:'.$b.',c:'.$c;
//a:0,b:0,c:1
$a=0;
$c=1;
$b=$a?$a:$c;
echo 'a:'.$a.',b:'.$b.',c:'.$c;
//a:0,b:1,c:1

Error while reading line from the server. [tcp://127.0.0.1:6379]

redis 加了代理 Twemproxy,而 predis 對這個配置默認執行 select 操做,致使了鏈接錯誤。node

你們之後要注意,若是 redis 有代理的話,別忘了把 'database' => 0,這個配置刪掉。
https://laravel-china.org/top...python

PHP empty 函數判斷結果爲空

class person
{
    protected $attributes = [];

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    public function __get($name)
    {
        return $this->attributes[$name] ?? null;
    }
}
https://laravel-china.org/articles/12530/the-shock-php-empty-function-is-empty-but-the-actual-value-is-nonempty

https://laravel-china.org/topics/3021/isset-is-not-right-after-upgrading-php7
var_dump(
    $person->firstName,
    empty($person->firstName),
    isset($person->firstName),
    is_null($person->firstName)
);

Laravel Redis 多個進程同時取隊列問題

Laravel 使用 Redis 的 list 做爲隊列的數據結構,並會爲每一個隊列分配一個 ID
Laravel 中入隊列方法mysql

public function pushRaw($payload, $queue = null, array $options = [])
{
 $this->getConnection()->rpush($this->getQueue($queue), $payload);
  
 return Arr::get(json_decode($payload, true), 'id');
}
用的是 Redis 的 rpush 命令。

Laravel 中取隊列方法
 
public function pop($queue = null)
{
 $original = $queue ?: $this->default; 
 $queue = $this->getQueue($queue); 
 $this->migrateExpiredJobs($queue.':delayed', $queue); 
 if (! is_null($this->expire)) {
  $this->migrateExpiredJobs($queue.':reserved', $queue);
 } 
 list($job, $reserved) = $this->getConnection()->eval(
  LuaScripts::pop(), 2, $queue, $queue.':reserved', $this->getTime() + $this->expire
 ); 
 if ($reserved) {
  return new RedisJob($this->container, $this, $job, $reserved, $original);
 }
}
這裏用的是 lua 腳本取隊列,以下:

 
public static function pop()
{
 return <<<'LUA'
local job = redis.call('lpop', KEYS[1])
local reserved = false
if(job ~= false) then
reserved = cjson.decode(job)
reserved['attempts'] = reserved['attempts'] + 1
reserved = cjson.encode(reserved)
redis.call('zadd', KEYS[2], ARGV[1], reserved)
end
return {job, reserved}
LUA;
}

那麼結論是:從 Laravel 的處理方式和打印的日誌結果看,即便多個進程讀取同一個隊列,也不會讀取到同樣的數據。nginx

隊列執行失敗以後根本不會執行failed方法

執行隊列偵聽器時加上 --tries參數便可,failed()方法只有在重試指定次數完成後纔會調用failed()方法如:
http://blog.zhouchenxi.cn/pos...
php artisan queue:listen --queue=default,listeners --tries=3
順便提一下:若是指定了隊列名稱必須在偵聽器的參數上加上 --queue參數才行,否則沒有指定的隊列是不會運行的。
event 指定隊列laravel

public $queue = 'listeners';
public function queue($queue, $job, $data)
       {
              if (isset($this->queue, $this->delay)) {
                     return $queue->laterOn($this->queue, $this->delay, $job, $data);
              }

              if (isset($this->queue)) {
                     return $queue->pushOn($this->queue, $job, $data);
              }

              if (isset($this->delay)) {
                     return $queue->later($this->delay, $job, $data);
              }

              return $queue->push($job, $data);
       }

php7不支持 preg_replace e修正符

車輪升級PHP7踩過的一些坑 http://php.swoole.com/wiki/%E...git

php5 php7不兼容的地方:https://segmentfault.com/a/11...github

$joinStr = preg_replace("/__([A-Z_-]+)__/e",$prex.".strtolower('$1')",$joinStr);
//替換爲
preg_replace_callback("/__([A-Z_-]+)__/",function($r) use (&$joinStr){
    $joinStr = $prex.strtolower($r[1]);
},$joinStr);

內存溢出

//https://laravel-china.org/articles/16312/handling-large-amounts-of-data-to-write-files-to-avoid-memory-overflow-and-response-timeout
$beginIndex = 0;
    $pageLimit = 50000;
    $endIndex = $beginIndex + $pageLimit;

    while ($pageData = \DB::connection('hub_log')->select("SELECT * FROM `{$tableName}` WHERE id > {$beginIndex} and id <= {$endIndex}")) {

        foreach ($pageData as $row) {
            file_put_contents(storage_path('mcd_rawdata/'.$tableName.'.txt'), $row->Content . "\n", FILE_APPEND);
        }

        $beginIndex += $pageLimit;
        $endIndex += $pageLimit;
    }
    
    $public_path = $time.'test.txt';

    DB::table('20171220')->orderBy('id')->chunk(10000,function($data) use ($public_path){
        $arr = '';
        foreach ($data->toArray() as $key => $value) {
            $arr .= $value->Content."\n";
        }

        file_put_contents(public_path($public_path),$arr, FILE_APPEND);
        unset($data);unset($arr);
    });

git bash 輸入python命令停滯

$ python -i
$ winpty python -3golang

保留兩位小數

round(a,2)
r = lambda f: f - f % 0.01
int(a*100)/100
print("%.2f" %a)

後期綁定

https://www.v2ex.com/t/482659...

def testFun():
    return(lambda x : i*x for i in range(4))
for everyLambda in testFun():
    print(everyLambda(2))
& python test.py
0
2
4
6
def testFun():
    temp = [lambda x : i*x for i in range(4)]
    return temp
for everyLambda in testFun():
    print(everyLambda(2))
& python test.py
6
6
6
6
第一個是括號(), 爲生成器, 返回 generator
第二個是中括號[], 爲列表生成式, 返回數組 列表表達式是即時計算的, 而生成器是迭代時纔會計算

{} + []

({}).valueOf() // []
// 返回來的是個對象,繼續調用 toString https://www.v2ex.com/t/480998#reply11
[].toString() // ""

[] + 1// "1"
[] + 'a' // "a"

echo 後發送 header

使用 fastcgi_finish_request();( PHP-fpm )能夠強制斷開客戶端鏈接 session 本質上是 header set-cookie,因此不算輸出。這裏的輸出指的是 response body 的部分
https://www.v2ex.com/t/481127...
clipboard.png

isset在php5.6-和php7.0+的一些差別

https://segmentfault.com/a/1190000016097997
class ProductCategory
{
    const TYPES = [
        1 => 'type1',
        2 => 'type2',  
    ];
    
    public function getType()
    {
        return isset(self::TYPES[$this->type]) ? self:TYPES[$this->type] : 'unrecognized_type';
    }
}
//把漢字拆分爲數組
function ch2arr($str)
{
    return preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY);
}

laravel 中使用 導出 excel 時報錯

PHPExcel_Calculation_Exception: Q5!A65 → Formula Error: An unexpected error occured in /application/www/web_git-pull/vendor/phpoffice/phpexcel/Classes/PHPExcel/Cell.php:291

緣由:

在excel中一個單元格若是是以=開頭,則說明這個單元格是根據其餘單元格的值算出來的,=後面必須跟着一個合法的表達式,而那個字符串是用戶的輸入,很明顯不該該是一個合法的表達式,因此應該在代碼中過濾掉

解決:
$str = "\t".$str;//同時解決 如 11111111111 顯示成 1.11111E+29
參考
https://github.com/Maatwebsit...
https://stackoverflow.com/que...

gzip UnicodeDecodeError

gzip解碼問題

clipboard.png

import urllib.request
import gzip

# 注意要先讀取內容才能夠解壓縮
data = urllib.request.urlopen(url).read()
try:
    html =data.decode("utf-8")
except:
    html =gzip.decompress(data).decode("utf-8")

Intervention/Image 圖片寫入中文

https://laravel-china.org/topics/13642/problems-encountered-in-writing-chinese-with-interventionimage-pictures-and-solutions
function to_unicode($string)
{
    $str = mb_convert_encoding($string, 'UCS-2', 'UTF-8');
    $arrstr = str_split($str, 2);
    $unistr = '';
    foreach ($arrstr as $n) {
        $dec = hexdec(bin2hex($n));
        $unistr .= '&#' . $dec . ';';
    }
    return $unistr;
}

獲取某字段修改前的值

Issue::saving(function(Issue $issue){
    if ($issue->isDirty('title')) {
        $user = Auth::user()->username;
        $oldTitle = $issue->getOriginal('title'); // 原始值
        $newTitle = $issue->title;                // 新值
        ActionLog::log("$user 把標題 $oldTitle 修改成 $newTitle");
    }
});

前一天

https://www.cnblogs.com/lhm166/articles/6066762.html
$mytime=mktime(0, 0, 0, date('m'), date('d')-1, date('Y'));//獲取時間戳
$mytime=date("Y-m-d H:i:s", strtotime("-1 day")); //獲取格式爲2016-12-30 13:26:13
$timetoday = strtotime(date("Y-m-d",time()));
function mdate($time = NULL) {
    $text = '';
    $time = $time === NULL || $time > time() ? time() : intval($time);
    $t = time() - $time; //時間差 (秒)
    $y = date('Y', $time)-date('Y', time());//是否跨年
    switch($t){
     case $t == 0:
       $text = '剛剛';
       break;
     case $t < 60:
      $text = $t . '秒前'; // 一分鐘內
      break;
     case $t < 60 * 60:
      $text = floor($t / 60) . '分鐘前'; //一小時內
      break;
     case $t < 60 * 60 * 24:
      $text = floor($t / (60 * 60)) . '小時前'; // 一天內
      break;
     case $t < 60 * 60 * 24 * 3:
      $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
      break;
     case $t < 60 * 60 * 24 * 30:
      $text = date('m月d日 H:i', $time); //一個月內
      break;
     case $t < 60 * 60 * 24 * 365&&$y==0:
      $text = date('m月d日', $time); //一年內
      break;
     default:
      $text = date('Y年m月d日', $time); //一年之前
      break;
    }
        
    return $text;
}function friend_date($time)
{
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //後天
    if ($d == 0) {
        $fdate = '剛剛';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '後天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分鐘前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小時前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}

phpstorm xdebug

https://www.cnblogs.com/baoch...
https://www.cnblogs.com/niuxi...
https://laravel-china.org/top...
https://laravel-china.org/art...
https://laravel-china.org/art...

若是出現Can't start listening for connections from 'xdebug': Port 9000 is busy
可修改端口號,要修改兩個地方
第一個地方是剛纔php.ini裏面的xdebug.remote_port=9000
第二個地方是phpstorm - setting - Languages&Frameworks - 相應的語言(好比PHP) - debug - 修改裏面的Debug port

Python for 循環中的陷阱

https://www.v2ex.com/t/470443...

pyinstaller 打包 exe

pyinstaller -p venv_path (中間必定要有空格) you.py https://www.v2ex.com/t/476247...
http://ju.outofmemory.cn/entr...

php捕獲fatal error

function fatal_handler() {
    $errfile = "unknown file";
    $errstr  = "shutdown";
    $errno   = E_CORE_ERROR;
    $errline = 0;
    $error = error_get_last();
    if($error){
      //發送郵件隊列也能夠http://www.iamtb.cn/2017/11/17/php-catch-fatel-error/
        file_put_contents('./testerror11.txt', json_encode($error));
    }
}
register_shutdown_function("fatal_handler");
try{
    $db=new db();
}catch(Exception $e){
echo $e->error_msg();
}

PHP7開始,含十六進制字符串再也不被認爲是數字

$str = "0xffff";//https://segmentfault.com/q/1010000004829059
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
    throw new Exception("Invalid integer!");
}
var_dump($int); // int(65535)
$t1 = 0x3FFFFFFF & (1 * (0xd5b42e11));
$t2 = 0x3FFFFFFF & (1 * (filter_var("0xd5b42e11", FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX)));

var_dump($t1,$t2);

php artisan config:cache

clipboard.png

cat config/sentry.php
return array(
    'dsn' => env('SENTRY_LARAVEL_DSN'),

    // capture release as git sha
    // 'release' => trim(exec('git log --pretty="%h" -n1 HEAD')),

    // Capture bindings on SQL queries
    'breadcrumbs.sql_bindings' => true,

    // Capture default user context
    'user_context' => false,

    //transport function
    'transport'=>function(Raven_Client $raven_Client,&$data){
        $raven_Client->setTransport(null);
          $raven_Client->close_curl_resource();
            \Queue::pushOn('sentry',new \App\Commands\sentry($raven_Client,$data));
        },
);

'transport'=>new \app\SentryTransport(),
class SentryTransport
{
    public static function __set_state($arr){
        return function($raven_Client,&$data){
            \Queue::pushOn('sentry',new \App\Commands\sentry($raven_Client,$data));
        };
    }
}

curl超時

//重試
$ch = curl_init();
// curl_setopt ($ch, CURLOPT_URL, 'produc_redis.php.com');
curl_setopt ($ch, CURLOPT_URL, '11.11.11.1');

https://segmentfault.com/a/1190000011188541
// I changed UA here
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_AUTOREFERER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 2);

$html = curl_exec($ch);

var_dump($html,curl_error($ch));

$num=3;
for($i=1;$i<=$num;$i++){
    if(curl_getinfo($ch,CURLINFO_HTTP_CODE)=='0' && $i<=$num){
      echo "retry $i 次".PHP_EOL;
      if($i==3){
          curl_setopt ($ch, CURLOPT_URL, '220.181.57.217');
      }
      $html = curl_exec($ch);
 }
}

var_dump($html);

var_dump(curl_error($ch));

// var_dump(curl_getinfo($ch));

/**
 * curl請求
 *https://segmentfault.com/a/1190000010197068
 * @param $url
 * @param string $postData
 * @param int $timeout
 * @return array|mixed
 * @throws Exception
 */
protected static function post($url, $postData = '', $timeout = 5)
{
    $ret = array();
    $times = 5;
    do {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        if ($postData != '') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        // 重要, 該處不能丟 curl 執行最大秒數
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $output = curl_exec($ch);
        if ($errNo = curl_errno($ch)) {
            error_log("Error [$errNo]: " . curl_error($ch));
        } else {
            $ret = json_decode($output, true);
            // 解析的結果集爲空時中止查詢
            if (!is_array($ret) && !trim($ret)) {
                throw new Exception(__METHOD__ . ": cURL調用失敗, 信息爲: " . $output);
            }
            unset($output);
        }
        curl_close($ch);
        if (isset($ret[0]) && $ret[0]) {
            return $ret;
        }
    } while ($times--);
    exit(__METHOD__ . ": cURL請求重試至 {$times} 次後仍無響應, 執行退出");
}

cURL error 28

cURL error 28: See http://curl.haxx.se/libcurl/c/libcurl-errors.html
$client=new GuzzleHttp\Client();
try {
    $tmp = $client->get($url,array("timeout"=>3,"connect_timeout"=>3));
    $res = json_decode(strval($tmp->getBody()),1);
} catch (\Exception $e) {
    $res = [];
    \Log::info('error', ['url' => $url, 'msg' => $e->getMessage()]);
}
$client=new GuzzleHttp\Client();
        $requests=[
            $client->createRequest('GET',$url,["timeout"=>3,"connect_timeout"=>3]),
            $client->createRequest('GET',$url2,["timeout"=>3,"connect_timeout"=>3]),
            
        ];
$result = Pool::batch($client, $requests, ['pool_size' => 2]);
//$result->getResult($requests[0]) instanceof GuzzleHttp\Message\Response
if ($result[0] instanceof Response && $result[0]->getStatusCode() == 200) {
            $data = json_decode($result[0]->getBody(), true);
  }

格式化

import prettytable as pt
https://www.v2ex.com/t/483984#reply15
## 按行添加數據
tb = pt.PrettyTable()
tb.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
tb.add_row(["Adelaide",1295, 1158259, 600.5])
tb.add_row(["Brisbane",5905, 1857594, 1146.4])
tb.add_row(["Darwin", 112, 120900, 1714.7])
tb.add_row(["Hobart", 1357, 205556,619.5])

print(tb)
 #str.ljust 和 rjust 纔是王道,誰用誰知道!

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
+-----------+------+------------+-----------------+

unicode

Unicode 每一個字符的詳情,能夠查官方文檔: https://www.unicode.org/charts/
python2 代碼:

for i in range(0x005b,0x005f):
print (unichr(i))#print (chr(i))
python3 代碼請查看 http://www.chenxm.cc/post/683...
unicode 字符表示方法 u + 16 進制數值,例如 u0001 print(''.join(chr(u) for u in range(0, 0x41))) u0040 這裏 0040 就是 16 進制的,range 是左閉右開的,因此u0020-u0040 的碼點範圍是 range(0x00, 0x40+1)
0b 二進制 0o 八進制 0x 16 進制
0b10 // 2
0o10 // 8
0x10 // 16
unicode 字符表示方法 u + 16 進制數值,例如 u0001
print(u'u0061') // ahttps://www.v2ex.com/t/484923...

laravel更新後讀取數據失敗

https://laravel-china.org/articles/16566/take-a-laravel-mysql-to-verify-the-experience-of-bug#reply62596
//建立數據
$meeting = meeting::create($data);

//查詢數據
$meeting = meeting::findOrFail($meeting->id);

//紀錄操做日誌
Log::insert($meeting);
線上數據庫是讀寫分離的,主庫寫入,但更新數據後立刻查詢,從庫可能沒來得及更新數據
當網絡很差時遇到從庫更新不及時 findOrFail 就會報 404,致使後面全部操做都失效,天然驗證也失效了
解決方法

更新完後,查詢指定使用主庫
更新後禁止查詢,直接使用 create 返回的 model 實例,對於數據庫中的有默認值的字段,手動加入到 model 實例中

批量更新

//https://laravel-china.org/topics/6864/how-to-batch-update-accumulate-a-field
https://laravel-china.org/articles/16620/laravel-project-execl-batch-import-database-data-update-data-no-insertion
$arr = [
// user_id => reward
  '1' => 50,
  '2' => 30,
  '3' => 60
];
User::find(array_keys($arr))->each(function ($query) use ($arr) {
  $query->increment('award' , $arr[$query->id]);
});
# 批量更新相同的 award
User::find(array_keys($arr))->each->increment('award', 30);

/**
         * 批量更新表的值,防止阻塞
         * @note 生成的SQL語句以下:
         * update mj_node set sort = case id
         *      when 13 then 1
         *      when 1 then 4
         *      when 7 then 5
         *      when 8 then 6
         *      when 9 then 7
         *      when 10 then 8
         *      when 11 then 9
         *      when 12 then 10
         * end where id in (13,1,7,8,9,10,11,12)
         * @param $conditions_field 條件字段
         * @param $values_field  須要被更新的字段
         * @param $conditions
         * @param $values
         * @return int
         */
        public function batchUpdate($conditions_field, $values_field, $conditions, $values)
        {
                $table = $this->model->getFullTableName();//返回完整表名,本身在項目中定義
                $sql   = 'update ' . $table . ' set '. $values_field .' = case ' .$conditions_field;
                foreach ($conditions as $key => $condition) {
                        $sql .= ' when ' . $condition . ' then ?';
                }
                $sql .= ' end where id in (' . implode(',', $conditions) . ')';
                return DB::update($sql, $values);//項目中須要引入DB  facade
        }

cat 多換行

https://www.v2ex.com/t/188162
調試shell腳本可使用 sh -x ****.sh,有詳細輸出內容
Bash的echo默認在末尾加了換行符"\n",因此你cat那個文件多了一個換行符,給echo加上-n參數就能不自動加換行符了。

var= cat tmp.txt;echo $var"abc" 改爲以下的形式

var= `cat tmp.txt`;echo $var"abc"或者 #注意不是單引號,是tab鍵上面1前面的那個符號
var=$(cat tmp.txt);echo $var"abc"

grep and or

https://blog.csdn.net/jackaduma/article/details/6900242
grep -E 'Tech|Sales' employee.txt
grep -v 'pattern1' filename
$ grep -E 'Manager.*Sales|Sales.*Manager' employee.txt  # -E 'pattern1.*pattern2'
egrep "php.*artisan.*$1"
egrep 'pattern1|pattern2' filename

memcached 默認的過時時間則 不能大於 30 天

https://laravel-china.org/top...

clipboard.png

cron 內容最後一行未回車

https://segmentfault.com/a/11... crontab -u www -e

unix:///tmp/supervisor.sock refused connection

[root@localhost supervisor]# supervisorctl -c /etc/supervisord.conf
unix:///tmp/supervisor.sock refused connection
supervisor> exit
 rm -f /tmp/supervisor.sock
[root@localhost supervisor]# ps aux|grep super
root        48  0.0  0.0      0     0 ?        S     2017   2:17 [sync_supers]
root      8246  0.0  0.1 208064 13404 ?        Ss   18:17   0:00 /usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf
supervisord是服務端,是個deamon,supervisorctl是客戶https://www.v2ex.com/t/210122
修改supervisor.conf文件後,要執行supervisorctl reload,從新加載配置文件
vi artisan.conf
[root@localhost supervisor]# supervisorctl status
unix:///tmp/supervisor.sock no such file
[root@localhost supervisor]# ps aux|grep super
root        48  0.0  0.0      0     0 ?        S     2017   2:17 [sync_supers]
root     19472  0.0  0.0 103256   844 pts/5    S+   19:57   0:00 grep super
[root@localhost supervisor]# supervisord -c /etc/supervisord.conf
Error: Invalid user name www in section 'program:artisan_queue' (file: '/etc/supervisor/artisan.conf')
For help, use /usr/bin/supervisord -h
[root@localhost supervisor]# vi /etc/supervisor/artisan.conf
[root@localhost supervisor]# supervisord -c /etc/supervisord.conf
[root@localhost supervisor]# supervisorctl status
artisan_queue                    BACKOFF   Exited too quickly (process log may have details)

http://blog.51cto.com/jxlwc/2112062 
https://www.jianshu.com/p/3658c963d28b

Specified key was too long

https://laravel-china.org/articles/17094/larave-admin-installation?#reply64528
默認的數據庫字符集,如今utf8mb4包括存儲emojis支持。若是你運行MySQL v5.7.7或者更高版本,則不須要作任何事情。
https://laravel-china.org/articles/4195/laravel-54-common-error-specified-key-was-too-long
https://segmentfault.com/a/1190000008416200
把config下的database.php下的mysql設置中,將'strict' => false就好了..
Schema::defaultStringLength(191); 是設置好的默認的字符串長度,也就是說,遷移中的字段沒有設置長度的話,varchar 字段會被默認成長度只有 191
use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

laravel with 查詢中只查詢個別字段

select 的時候沒有 id 的話就會爲 null https://laravel-china.org/articles/17379
public function brand()
 {
        return $this->belongsTo(Brand::class, 'brandId')->select('id', 'briefCode');
 }
 $result = Brand::with(['brand' =>  function($query){
    $query->select('id', 'briefCode');
}])->get();

PHP輸出A到Z

for($i='A'; $i<='Z'; $i++)
{
    echo $i . '<br>';
}
for($i=ord('A'); $i<=ord('Z'); $i++)
{
    echo chr($i) . '<br>';
}
for($i = 'A'; $i != 'BB'; $i++)
{
    echo $i . '<br>';
}

$al = 'A';
while($al != 'BB')
{
    echo $al++ . '<br>';
}

env函數的小坑

dump(env('APP_ENV') === null); // true 
由於沒有執行 config:cache 命令,而項目上線後爲了優化訪問速度,生成了緩存文件,致使env取值失敗
若是使用了config:cache,env函數只能在config目錄下的配置文件的php裏使用,不能夠在其餘地方使用。

一個很是簡單的辦法就是將
env('APP_ENV')改成config('app.env')
config函數會優先讀取 bootstrap/cache/config.php 中緩存的配置,若是沒有緩存文件,則會直接讀取 config 目錄下的全部配置文件
https://www.jianshu.com/p/83f9cd407751

任務調度的列表

//1. 加載Console內核
app()->make(\Illuminate\Contracts\Console\Kernel::class);

//2.  獲取計劃任務列表
$scheduleList = app()->make(\Illuminate\Console\Scheduling\Schedule::class)->events();

在模型事件中獲取某字段修改前的值

Issue::saving(function(Issue $issue){
    if ($issue->isDirty('title')) {
        $user = Auth::user()->username;
        $oldTitle = $issue->getOriginal('title'); // 原始值https://laravel-china.org/wikis/16169
        $newTitle = $issue->title;                // 新值
        ActionLog::log("$user 把標題 $oldTitle 修改成 $newTitle");
    }
});

laravel SerializesModels

由於咱們在任務類裏引用了 SerializesModels 這個 trait,使得 Eloquent 模型在處理任務時能夠被優雅地序列化和反序列化。若是你的隊列任務類在構造器中接收了一個 Eloquent 模型,那麼只有可識別出該模型的屬性會被序列化到隊列裏。當任務被實際運行時,隊列系統便會自動從數據庫中從新取回完整的模型。這整個過程對你的應用程序來講是徹底透明的,這樣能夠避免在序列化完整的 Eloquent 模式實例時所帶來的一些問題。https://laravel-china.org/top...

composer require失敗

cat composer.json
"monolog/monolog": "^2.0@dev",

$ composer require dees040/laravel-api-responses
    1/1:        https://packagist.laravel-china.org/p/provider-latest$0449728151603                       e355a0ee137fb34881e699652e41e3e1de11ba9c4ea7a47a312.json
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Using version dev-master for dees040/laravel-api-responses
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package monolog/monolog (locked at 1.23.0, required as ^2.0@dev                       ) is satisfiable by monolog/monolog[1.23.0] but these conflict with your requiremen                       ts or minimum-stability.
  Problem 2
    - laravel/framework v5.5.42 requires monolog/monolog ~1.12 -> satisfiable by mo                       nolog/monolog[1.x-dev].
    - laravel/framework v5.5.42 requires monolog/monolog ~1.12 -> satisfiable by mo                       nolog/monolog[1.x-dev].
    - laravel/framework v5.5.42 requires monolog/monolog ~1.12 -> satisfiable by mo                       nolog/monolog[1.x-dev].
    - Can only install one of: monolog/monolog[2.x-dev, 1.x-dev].
    - Installation request for monolog/monolog ^2.0@dev -> satisfiable by monolog/m                       onolog[2.x-dev].
    - Installation request for laravel/framework (locked at v5.5.42, required as 5.                       5.*) -> satisfiable by laravel/framework[v5.5.42].
    
$composer require "monolog/monolog:~1.12"
    1/1:        https://packagist.laravel-china.org/p/provider-latest$d12a81f48a3e1dad512c1d2c375298e3a8ea414dff5000d5f345939429c6b29b.json
    Finished: success: 1, skipped: 0, failure: 0, total: 1
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/1:        https://dl.laravel-china.org/monolog/monolog/c465e1144536862e03f519cb3d65e924062cabfb.zip
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Package operations: 0 installs, 1 update, 0 removals
  - Removing monolog/monolog (1.23.0)
  - Installing monolog/monolog (1.x-dev c465e11):
Cloning c465e11445 from cache
Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead.
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
Discovered Package: 96qbhy/hyid
Discovered Package: appstract/laravel-opcache
Discovered Package: appstract/lush-http
Discovered Package: barryvdh/laravel-debugbar
Discovered Package: barryvdh/laravel-dompdf
Discovered Package: barryvdh/laravel-ide-helper
Discovered Package: base62/base62
Discovered Package: cblink/laravel-excel-zip
Discovered Package: cblink/laravel-sso
Discovered Package: chumper/zipper
Discovered Package: encore/laravel-admin
Discovered Package: encore/redis-manager
Discovered Package: fideloper/proxy
Discovered Package: foryoufeng/laravel-generator
Discovered Package: ibrand/laravel-miniprogram-poster
Discovered Package: intervention/image
Discovered Package: itsgoingd/clockwork
Discovered Package: jacobcyl/ali-oss-storage
Discovered Package: jellybool/flysystem-upyun
Discovered Package: jenssegers/agent
Discovered Package: jenssegers/mongodb
Discovered Package: laravel-admin-ext/helpers
Discovered Package: laravel/tinker
Discovered Package: latrell/lock
Discovered Package: lubusin/laravel-decomposer
Discovered Package: maatwebsite/excel
Discovered Package: nesbot/carbon
Discovered Package: overtrue/laravel-query-logger
Discovered Package: overtrue/laravel-socialite
Discovered Package: prettus/l5-repository
Discovered Package: sentry/sentry-laravel
Discovered Package: simplesoftwareio/simple-qrcode
Discovered Package: spatie/laravel-tail
Discovered Package: tymon/jwt-auth
Discovered Package: zgldh/qiniu-laravel-storage
Package manifest generated successfully.

$ composer require dees040/laravel-api-responses
    1/1:        https://packagist.laravel-china.org/p/provider-latest$14d9ca1b35af157c565d6c564cde71c59043d7457135c5a4317471625a1db2e7.json
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Using version dev-master for dees040/laravel-api-responses
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/1:        https://dl.laravel-china.org/dees040/laravel-api-responses/9aec7eb323fc45e17f1dbb9c6e203d240836f91b.zip
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Package operations: 1 install, 0 updates, 0 removals
  - Installing dees040/laravel-api-responses (dev-master 9aec7eb): Cloning 9aec7eb323 from cache
Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead.
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

$ composer require phpoffice/phpspreadsheet
    1/2:        https://packagist.laravel-china.org/p/provider-latest$8512051929ea08e8189e440a1f5293135717f61525e93d6f4577794143032dd5.json
    2/2:        https://packagist.laravel-china.org/p/provider-2018-10$4f971ac341cf575b7ed47aa09773abb926ec0c2baad56a0da2c9eed868beb649.json
    Finished: success: 2, skipped: 0, failure: 0, total: 2
Using version dev-master for phpoffice/phpspreadsheet
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - maatwebsite/excel 3.0.9 requires phpoffice/phpspreadsheet ^1.2 -> satisfiable by phpoffice/phpspreadsheet[1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.5.0] but these conflict with your requirements or minimum-stability.
    - maatwebsite/excel 3.0.9 requires phpoffice/phpspreadsheet ^1.2 -> satisfiable by phpoffice/phpspreadsheet[1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.5.0] but these conflict with your requirements or minimum-stability.
    - maatwebsite/excel 3.0.9 requires phpoffice/phpspreadsheet ^1.2 -> satisfiable by phpoffice/phpspreadsheet[1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.5.0] but these conflict with your requirements or minimum-stability.
    - Installation request for maatwebsite/excel (locked at 3.0.9) -> satisfiable by maatwebsite/excel[3.0.9].


Installation failed, reverting ./composer.json to its original content.

suping3@BJ-D-212361A MINGW64 /d/code/blog
$ composer require "phpoffice/phpspreadsheet:^1.2"
    1/3:        https://packagist.laravel-china.org/p/provider-2018-10$edb575ac09ff566f26e69fb52521dbd7b5bd90cb0e97c11c04a834f1ba157b0b.json
    2/3:        https://packagist.laravel-china.org/p/provider-latest$f7aba8aec5290950424531a654a2519842e07f0dcd995755aa8e64e7f622ad17.json
    3/3:        https://packagist.laravel-china.org/p/provider-2018-07$1f1ac5377ce1027162f91a3db54217c36e38f7ae18744629e6e89c5e6d410c78.json
    Finished: success: 3, skipped: 0, failure: 0, total: 3
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/1:        https://dl.laravel-china.org/phpoffice/phpspreadsheet/2dfd06c59825914a1a325f2a2ed13634b9d8c411.zip
    Finished: success: 1, skipped: 0, failure: 0, total: 1

Fatal error: Class 'PHPUnit_Framework_TestCase' not found

https://github.com/dees040/laravel-api-responses/issues/2
vi vendor/dees040/laravel-api-responses/tests/ResponseTest.php

class ResponseTest extends \PHPUnit\Framework\TestCase

$ phpunit vendor/dees040/laravel-api-responses/tests/ResponseTest.php
PHPUnit 6.5.3 by Sebastian Bergmann and contributors.

..............                                                    14 / 14 (100%)

Time: 378 ms, Memory: 16.00MB

Laravel 的 collection

$collection = new \Illuminate\Database\Eloquent\Collection(['item a', 'item b', 'item c']);
$collection = $collection->unique();
執行時候會報錯

PHP Fatal error:  Call to a member function getKey() on string in /Project/nginx/webbpm-dev.ssl.lol/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php on line 259

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Call to a member function getKey() on string
這是由於 Illuminate\Database\Eloquent\Collection 經過調用自身的 getDictionary 方法,使用根據主鍵去重複的邏輯覆蓋了 Illuminate\Support\Collection 的邏輯。

以上代碼改爲https://laravel-china.org/topics/18696

$collection = collect(['item a', 'item b', 'item c']);
$collection = $collection->unique();

使用"mews/captcha:~2.0" 驗證碼圖片不顯示問題

Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined function Intervention\Image\Gd\imagettfbbox() in file /usr/share/nginx/html/LaraBBS/vendor/intervention/image/src/Intervention/Image/Gd/Font.php on line 85

若是已經開啓了gd,請參考下 https://laravel-china.org/articles/18815?#reply69185 

FROM php:7.0-fpm
RUN apt-get update && apt-get install -y \
libfreetype6-dev \
libjpeg62-turbo-dev \
libmcrypt-dev \
libpng-dev \
&& docker-php-ext-install -j$(nproc) iconv mcrypt \
&& docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
&& docker-php-ext-install -j$(nproc) gd

在解析外部變量時的一個問題

//https://segmentfault.com/a/1190000017051950
<form method="post">
    <input type="text" name="id[]" value="1">
    <input type="text" name="id[]_text" value="a">
    <input type="text" name="id[]" value="2">
    <input type="text" name="id[]_text" value="b">
    <input type="submit">
</form>
var_export($_POST);
array (
  'id' => 
  array (
    0 => '1',
    1 => 'a',
    2 => '2',
    3 => 'b',
  ),
)
$foo["id"] = 1;
$foo["id[]_text"] = 2;

var_export($foo);

extract($foo);

var_export(get_defined_vars());

Laravel with () limit

好比如何取得每篇文章中的前10條評論
下面爲錯誤寫法:https://laravel-china.org/articles/19932

essay::with(['comment' => function($query) {
    $query->take(10)
}])
public function products()
{
    return $this->belongsToMany(Hproduct::class,'hproduct_has_type','type_id','product_id');
}

public function topTenproducts()
{
    return $this->products()->with('supplier')->where('is_sale','=',1)->limit(4);
}

public function getProdcutsWithtopTenproducts($col)
{
    $model = $this->whereIn('id',$col)->get();
    $model->each(function ($model) {
        $model->load('topTenproducts');
        });
    return $model->toArray();
}

laravel 5.5 索引長度超過限制

laravel5.4中改變了默認的編碼類型(utf8 => utf8mb4), 從而使email字段索引長度超過了的默認限制長度 https://laravel-china.org/articles/18306
InnoDB 引擎中:

uft8 varchar 最大長度 255
utf8mb4 varchar 最大長度 191
設置一下 varchar 的長度不超過 191 便可
 table->string('email')->index(); varchar會使用utf8mb4編碼, utf8mb4編碼(4bytes)屬於utf8編碼(3bytes)的擴展類型,
由此能夠計算索引長度爲255*4+2=1022 >767
$ php artisan migrate
Migration table created successfully.

In Connection.php line 664:

  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t
  oo long; max key length is 1000 bytes (SQL: alter table `users` add unique
  `users_email_unique`(`email`))

golang序列化失敗

ret, _ := json.Marshal(result)//https://www.hchstudio.cn/article/2018/2622/
發現是結構體定義有問題,當定義結構體時首字母必須大寫才能序列化成功,這個特色在golang裏面非常明顯,在函數調用時首字母小寫的函數在其餘文件裏面是調不到的。下面給出正確的結構體定義
type ResultCode struct {
    Msg  string `json:"msg"`
    Code int    `json:"code"`
    Data string `json:"data"`
}
相關文章
相關標籤/搜索