PHP Lumen - 入门教程 - 简单架子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wowkk/article/details/52144951

局域网访问Apache

制作API,本地测试完,就得给APP他们使用了,不想部署到服务器那么麻烦的话,可以修改配置,让局域网内可以访问。
Apache/conf目录下的httpd.conf新增

Listen 192.168.0.135:8080
<VirtualHost 192.168.0.135:8080>
    DocumentRoot "H:/xampp/htdocs/PDK-API/public"
</VirtualHost>

路由

我讨厌的事情之一就是维护很多的路由管理规则。

API请求统一为Post请求,为什么要分什么Get,Post,Put,Delete?又不是restful,统一使用Post请求只是觉得这样至少不可以直接在浏览器访问。

<?php

$app->group(["namespace"=>"App\Http\Controllers"], function()use($app){
    //账户控制器
    $app->post("/AccountController/{Type}",["uses" => "AccountController@Index"]);
    //资讯控制器
    $app->post("/NewsController/{Type}",["uses" => "NewsController@Index"]);

    //web测试。方便调试,生产环境中会注释掉这些代码
    $app->get("/AccountController/{Type}",["uses" => "AccountController@Index"]);
    $app->get("/NewsController/{Type}",["uses" => "NewsController@Index"]);
});

这样的话,每个请求都要指定用哪个控制,但统一指定”Index”方法。在”Index”里面再去“分流”处理请求。

Model

数据库操作有时有坑,最好指定表名和主键。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class information extends Model
{
    protected $table = 'informations'; //指定操作表名
    protected $primaryKey = "information_id";  //指定主键
}

控制器

<?php

namespace App\Http\Controllers;

use App\Models\Information;
use App\Models\Collection;
use App\Models\User;

use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class NewsController extends BaseController
{
    function Index(Request $request,$Type){
        $responseData = [
            "State" => "Fail",
            "Value" => "传入有误"
        ];
        //获取资讯列表
        if($Type == "getList"){
            $information = new Information;
            $page = (int)$request->page;
            $list = $information->orderBy('created_at', 'desc')->forPage($page,10)->get();
            //……省略代码……
            $responseData["list"] = $list;
            return json_encode($responseData, JSON_UNESCAPED_UNICODE);//统一响应格式
        }
        //获取资讯  详情
        else if($Type == "getInformation"){
            //……省略代码……
        }
        //收藏资讯
        else if($Type == "collectInformation"){
            //判断是否登录
            $user = new User;
            $loginUser = $user->LoginUser($request->username, $request->token);//可以在Model类扩展函数
            if(!$loginUser){
                $responseData["State"] = "NeedLogin";
                $responseData["Value"] = "请重新登录";
                return json_encode($responseData, JSON_UNESCAPED_UNICODE);
            }
            //收藏资讯
            //……省略代码……
            $responseData["State"] = "Success";
            $responseData["Value"] = "收藏成功";
            return json_encode($responseData, JSON_UNESCAPED_UNICODE);
        }
        return json_encode($responseData, JSON_UNESCAPED_UNICODE);
    }
}

这样的架子,虽然路由表简单多了,但是控制器相对复杂了。当然需要的话可以精简精简。

猜你喜欢

转载自blog.csdn.net/wowkk/article/details/52144951