天天看點

十分鐘上線-函數計算&Laravel的那些事兒

前言

這個文章介紹方案過時, 直接參考自定義鏡像方案

函數計算目前已經支援了

自定義鏡像

, 感興趣的同學直接使用鏡像體驗更流暢,使用 custom-container, 和傳統的 php 使用方法一緻, 通過 S 工具可以一鍵部署

start-laravel start-thinkphp start-zblog start-wordpress start-discuz

@Deprecated

注意: 可以直接參考最新的官方文檔:

遷移 larvel 到函數計算

這篇文章是

十分鐘上線-函數計算玩轉 WordPress

的姊妹篇,有關函數計算的優勢,php runtime 運作php 架構原理等相關内容可以先預覽

,本文假設您已經了解函數計算 php runtime, vpc, nas, 自定義域名等相關内容的基礎上,我們通過将github上一個star很高的larvel入門部落格教程

Learn-Laravel-5

項目移植到在函數計算上, 展示函數計算環境驅動laravel的能力,實作 laravel web 項目 serverless 化。

案例體驗入口:

FC 運作larvel 流程

  • 下載下傳 ,準備好mysql資料庫。
    • 修改.env, 主要是修改資料庫連接配接相關内容
    DB_CONNECTION=mysql
    DB_HOST=rm-xxyyyy12583ck110swao.mysql.rds.aliyuncs.com
    DB_PORT=3306
    DB_DATABASE=fc-larvel
    DB_USERNAME=haha
    DB_PASSWORD=pwd123456           
    • php artisan migrate

      ,做資料庫初始化工作
    • chmod -R 777 storage

      chmod -R 777 bootstrap/cache

      , 保證這兩個目錄可寫
    • 執行指令

      php artisan key:generate

      ,生成app_key
  • 将 Learn-Laravel-5 工程移到上述配置的 NAS 中, www 表示 Learn-Laravel-5 的工程的根目錄。
|-- index.py
|-- www           

index.py代碼:

# -*- coding: utf-8 -*-
import logging  
import os

file = "/mnt/www/"

def mkdir(path):
  folder = os.path.exists(path)
  if not folder:                  
    os.makedirs(path)           
    
def lsDir():
  os.system("ls -ll /mnt/www/")

def handler(event, context):
  mkdir(file)  
  os.system("cp -r /code/www/* /mnt/www/")
  os.system("cp -a /code/www/.env /mnt/www/.env")
  print(lsDir())
  return 'ok'           

基于上述代碼創一個函數

move-larvel-nas

, 執行函數,将 Learn-Laravel-5 工程包移動到 NAS 的

/mnt/www/

目錄。

注: 在第一步初始化的時候,可以使用資料庫的公網位址; 在函數計算的環境中,使用vpc,可以修改.env, 将其改為内網位址,更加安全
  • 編寫函數,代碼如下:

    laravel 是單入口架構,所有的url都是經過

    public/index.php

    <?php
    use RingCentral\Psr7\Response;
    
    function startsWith($haystack, $needle) {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }
    
    function handler($request, $context): Response{
        $uri    = $request->getAttribute("requestURI");
        
        $isPhpScript = false;
        $root_dir = '/mnt/www';
        $filename = $root_dir . explode("?", $uri)[0];
        $filename = rawurldecode($filename);
        
        $pathinfo  = pathinfo($filename);
        if(!isset($pathinfo['extension'])){
          $isPhpScript = true;
        }else{
          $extension = strtolower($pathinfo['extension']);
          if($extension == 'php'){
            $isPhpScript = true;
          }
        }
        
        $proxy    = $GLOBALS['fcPhpCgiProxy'];
        //php script
        if ($isPhpScript) {
            $host   = "rayzhang.mofangdegisn.cn";
            $resp   = $proxy->requestPhpCgi($request, $root_dir, "index.php",
                ['SERVER_NAME' => $host, 'SERVER_PORT' => '80', 'HTTP_HOST' => $host,
                'SCRIPT_FILENAME' => $root_dir . "/public/index.php",
                    'SCRIPT_NAME' => "/index.php"],
                ['debug_show_cgi_params' => true, 'readWriteTimeout' => 20000]
            );
            return $resp;
        } else {
            // static files, js, css, jpg ...
            $handle   = fopen($filename, "r");
            $contents = fread($handle, filesize($filename));
            fclose($handle);
            $headers = [
                'Content-Type'  => $proxy->getMimeType($filename),
                'Cache-Control' => "max-age=8640000",
                'Accept-Ranges' => 'bytes',
            ];
            return new Response(200, $headers, $contents);
        }
    }           
  • 給函數入口配置自定義域名(操作過程請參考: 綁定自定義域名示例 ), 具體配置假設如下:
十分鐘上線-函數計算&amp;Laravel的那些事兒
注意: 綁定自定義域名之後,不用使用控制台來進行調試,就隻能使用浏覽器來觸發函數,日志服務來進行調試。

總結

FC 可以做為 Web Backend,隻需要編寫一個函數實作傳統 Web 伺服器中的 conf 中的邏輯,就可以将一個完整的 Web 工程遷移到 FC ,進而從傳統的 Web 網站運維,監控等繁瑣的事務中解放出來。

最後歡迎大家通過掃碼加入我們使用者群中,搭建過程中有問題或者有其他問題可以在群裡提出來。

函數計算官網客戶群(11721331)。

十分鐘上線-函數計算&amp;Laravel的那些事兒