laravel前后端分离笔记一

臭大佬 2019-11-15 12:35:23 2495
php  laravel 
简介 laravel前后端分离笔记

起因

最近有个高防的项目需要使用前后端分离去做,这一块我觉得很有必要做一下笔记,因为后期,我的laravel-wjfcms这个系统也想采用这种前后端分离的形式去弄。

优势

可以实现真正的前后端解耦

术业有专攻,前端可以专注于前端的事,后端就专心研究后端的技术,我就在这吃了大亏。前段时间写前端页面快把我给写挂了。希望后端以后再也不用写那些js和css了,太难了。
前端页面渲染,然后以接口的形式获取数据,这样,后端的可扩展性就很强了,比如博主最近在学习Go,如果是前后端分离的话,后期我就可以直接用Go去作为接口返回数据给前端页面了,不需要重写整个项目。

初始化项目

拉取项目

我们打开E:\wwwroot\laravel\dev.lar.net目录,这是我放置代码的目录,根据自己需求配置,使用composer拉取

composer create-project --prefer-dist laravel/laravel blog

.env.example 复制一份命名为.env,然后设置一下数据库连接。

设置项目key

 php artisan key:generate

编辑项目下的数据迁移文件,添加我们需要的字段

 //2014_10_12_000000_create_users_table.php
 /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id')->comment('用户表');
            $table->string('name')->comment('用户昵称');
            $table->text('last_token')->comment('登陆时的token');
            $table->tinyInteger('status')->default('0')->comment('用户状态 -1代表已删除 0代表正常 1代表冻结');
            $table->string('email',150)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

注意,数据迁移文件有uniques()的字段都需要设置长度,不然会报如下错误:

每个问价都打开设置后再运行 php artisan migrate

然后把blog里面的内容剪切到dev.lar.net目录下,再删除blog。

配置网站

我本地用的是phpstudy配置,如果您也是使用这个配置环境的话,可以参考我这篇进行配置 phpStudy+nginx配置laravel伪静态

模型

然后把app目录下的User.php移动到Models目录下
运行如下命令,生成User模型:

 php artisan make:model /Models/User

然后把app/User.php文件内容复制到新建的Models/User内,修改命名空间为namespace App\Models; //这里从App改成了App\Models

最后文件/Models/User.php代码 如下:

 <?php
namespace App\Models; //这里从App改成了App\Models

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mas assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','last_token'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Description:将密码进行加密
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/11/15
     * Time: 10:49
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}

查找项目中的App\User进行替换App\Models\User

控制器

首先自己创建一个放回的json格式,在app/Http/Controller.php加上如下方法:

  /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/11/15
     * Time: 11:53
     * @param int $code
     * @param string $msg
     * @param null $data
     * @param array $additional
     * @param array $header
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    protected function resJson($code = 0, $msg = '', $data = null, array $additional = [], array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        if (count($additional) > 0) {
            foreach ($additional as $key => $val) {
                $result[$key] = $val;
            }
        }
        $result['create_time'] = date('Y-m-d H:i:s', time());
        return response($result)->withHeaders($header);
    }

创建API控制器

php artisan make:controller Api/UserController

代码如下:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/11/15
     * Time: 10:57
     * @param Request $request
     * @return string
     */
    public function index(Request $request)
    {
        return '测试API';
    }
}

路由

Http/Controllers/Api对应的路由在routes/api.php里面设置,
我们给路由添加一个 prefix 是为了版本号,方便后期接口升级区分。

Route::namespace('Api')->prefix('v1')->group(function () {
    Route::get('/users','UserController@index')->name('users.index');
});

访问结果

API工具访问

创建验证器

在创建用户之前,我们先创建验证器,来让我们服务器接收到的数据更安全。当然,我们也要把关于 Api 验证的放在一个专门的文件夹内。

创建一个 Request 的基类

php artisan make:request RequestPost

修改访问权限,最终文件代码如下:

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Auth;

class RequestPost extends FormRequest
{
    /**
     * @var
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/21
     * Time: 11:18
     */
    protected $msg;

    /**
     * Determine if the user is authorized to make this request.
     * 判断用户是否有权限做出此请求。
     *
     * @return bool
     */
    public function authorize()
    {
//        $user = Auth::user();
//        if ($user->is_admin) {
//            return true;
//        } else {
//            $this->getFailedResponse('该操作未经授权');
//        }
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }

    /**
     * Description:设置错误信息
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/21
     * Time: 11:17
     * @param $msg
     * @return $this
     */
    protected function setMsg($msg)
    {
        $this->msg = $msg;
        return $this;
    }

    /**
     * Description:返回错误相应
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/21
     * Time: 11:21
     * @param string $msg
     * @param int $code
     * @param null $data
     * @param int $status
     */
    protected function getFailedResponse($msg = '', $code = 0, $data = null, $status = 200)
    {
        throw (new HttpResponseException(response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ], $status)));
    }

    /**
     * Description:返回错误信息
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/16
     * Time: 16:06
     * @param Validator $validator
     */
    protected function failedValidation(Validator $validator)
    {
        $this->getFailedResponse($validator->errors()->first());
    }
}

创建关于 UserController 的专属验证器,并让它继承RequestPost基类

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Auth;

class BaseRequest extends FormRequest
{
    /**
     * @var
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/21
     * Time: 11:18
     */
    protected $msg;

    /**
     * Determine if the user is authorized to make this request.
     * 判断用户是否有权限做出此请求。
     *
     * @return bool
     */
     public function authorize()
    {
        //false代表权限验证不通过,返回403错误
        //true代表权限认证通过
        //$user = Auth::user();
        //if ($user->is_admin) {
        //  return true;
        //} else {
        //  $this->getFailedResponse('该操作未经授权');
        //}
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }

    /**
     * Description:设置错误信息
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/21
     * Time: 11:17
     * @param $msg
     * @return $this
     */
    protected function setMsg($msg)
    {
        $this->msg = $msg;
        return $this;
    }

    /**
     * Description:返回错误相应
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/21
     * Time: 11:21
     * @param string $msg
     * @param int $code
     * @param null $data
     * @param int $status
     */
    protected function getFailedResponse($msg = '', $code = 0, $data = null, $status = 200)
    {
        throw (new HttpResponseException(response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ], $status)));
    }

    /**
     * Description:返回错误信息
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/10/16
     * Time: 16:06
     * @param Validator $validator
     */
    protected function failedValidation(Validator $validator)
    {
       $this->getFailedResponse($validator->errors()->first());
    }
}

创建数据

现在我们来编写创建用户接口,在UserController增加两个方法,并增加两条路由

// app/Http/Controllers/Api/UserController.php
/**
     * Description:用户注册
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/11/15
     * Time: 11:31
     * @param UserRequest $request
     * @return string
     */
    public function store(UserRequest $request)
    {
        User::create($request->all());
        return '用户注册成功。。。';
    }

    /**
     * Description:用户登录
     * User: Vijay <1937832819@qq.com>
     * Date: 2019/11/15
     * Time: 11:32
     * @param Request $request
     * @return string
     */
    public function login(Request $request)
    {
        $res = Auth::guard('web')->attempt(['name' => $request->name, 'password' => $request->password]);
        if ($res) {
            return '用户登录成功...';
        }
        return '用户登录失败';
    }
Route::namespace('Api')->prefix('v1')->group(function () {
    Route::get('/users','UserController@index')->name('users.index');

    Route::post('/users','UserController@store')->name('users.store');
    Route::post('/login','UserController@login')->name('users.login');
});

用API工具添加数据