1. 程式人生 > >用阿里雲函式計算部署thinkphp5.1

用阿里雲函式計算部署thinkphp5.1

thinkphp國內還是用的很多的哈,我自己就用哈。所以研究了一下用函式計算部署tp5。
其中借鑑和學習了@rsong 的文章:《十分鐘上線-函式計算玩轉 WordPress

這裡是TP5的演示:https://31199382.cn-beijing.fc.aliyuncs.com/2016-08-15/proxy/web-site/tp5/
其實也沒什麼好演示的,就是純淨的tp5 ( ̄▽ ̄)~*

步驟:

1.後臺建立php7.2環境的函式,建立http觸發器,這些就不詳細寫了,可以去看文件。

2.開啟tp5的入口檔案(/public/index.php)在namespace think; 這句的下面,加如下程式碼:

if(!$_SERVER['PATH_INFO']) $_SERVER['PATH_INFO'] = preg_replace("/^(\?s\=\/)/","",$_SERVER['REQUEST_URI']);

3.準備tp5原始碼,在根目錄建立index.php檔案(作為函式的入口檔案),程式碼如下:
(第一次在阿里雲部落格上寫文章哈,有點手生)

<?php
#自定義的域名,綁定了自定義域名的,可以換成自己自定義的。
$MY_HOST    = "31199382.cn-beijing.fc.aliyuncs.com";
#web目錄,預設是tp5的public目錄,絕對路徑,如:/code/public
$WWW_DIR = '/code/public';

function handler($request, $context){

    #如果不使用函式計算後臺提供的那個廠廠的域名,這句可以註釋掉。
    if(strpos($request->getAttribute("requestURI"),"/2016-08-15/proxy") !== false) $request = clearFcHost($request,$context);#相容 fc後臺的url地址

    $uri  = $request->getAttribute("requestURI");
    $file = explode("?", $uri)[0];
    if($file=='/') $uri='/';#
    $file = $GLOBALS['WWW_DIR'].$file;

    if(file_exists($file) and $uri!='/'){
        if(strpos($uri,".php")) return php_run(basename($file), $request, $context);#php_run
        return static_run($uri);#static_run
    }

    $request = $request->withAttribute("requestURI", "?s=".$uri);
    return php_run('index.php', $request, $context);# php_run

}

function php_run($name,$request, $context)
{
    return $GLOBALS['fcPhpCgiProxy']->requestPhpCgi($request, $GLOBALS['WWW_DIR'], $name,['SERVER_NAME' => $GLOBALS['MY_HOST'], 'SERVER_PORT' => '80', 'HTTP_HOST' => $GLOBALS['MY_HOST']],['debug_show_cgi_params' => false, 'readWriteTimeout' => 15000]);
}
use RingCentral\Psr7\Response;
function static_run($uri): Response{
    $file_dir = $GLOBALS['WWW_DIR'].$uri; #完整檔案路徑
    $file_dir = explode("?", $file_dir)[0]; #去掉動態路徑
    if(is_dir($file_dir)) $file_dir .= '/index.html';# 可以這裡定義目錄的預設索引頁
    $handle   = fopen($file_dir, "r");
    $contents = fread($handle, filesize($file_dir));
    fclose($handle);
    return new Response(200, ['Content-Type'  => $GLOBALS['fcPhpCgiProxy']->getMimeType($file_dir),'Cache-Control' => "max-age=8640000",'Accept-Ranges' => 'bytes'], $contents);
}

function clearFcHost($request,$context){
    $uri  = $request->getAttribute("requestURI");
    $uri  = str_replace("/2016-08-15/proxy/".$context['service']['name']."/".$context['function']['name'],"",$uri);
    $request = $request->withAttribute("requestURI", $uri);
    return $request;
}

#錯誤處理
function error($code) {
    #if($resp->getStatusCode() !=200) return error($resp->getStatusCode());
    return '這裡還木有寫哈~~';
}

4.由於函式計算只有/tmp 目錄可寫,所以要改一下tp5的配置檔案
編輯/config/log.php

'path'  => '/tmp/log',

編輯/config/cache.php

'path'  => '/tmp/cache',

好了,至此就部署好了。

ps.簡單的測試了一下,應該沒什麼問題。首次釋出在阿里雲部落格,有什麼問題請來原文留言哈。