前言
Lumen是一個基於Laravel的微框架,號稱是以速度爲生。截用Lumen官網的一段,號稱是比silex和slim還要快。php
本文將用Lumen來實現一個完整的用戶註冊、登陸及獲取用戶信息的API。mysql
Lumen官方網站:https://lumen.laravel.com/
Lumen中文網站:http://lumen.laravel-china.org/laravel
Lumen是一個基於Laravel的微框架,號稱是以速度爲生。截用Lumen官網的一段,號稱是比silex和slim還要快。php
本文將用Lumen來實現一個完整的用戶註冊、登陸及獲取用戶信息的API。mysql
Lumen官方網站:https://lumen.laravel.com/
Lumen中文網站:http://lumen.laravel-china.org/laravel
composer create-project --prefer-dist laravel/lumen lumen
|
跟全棧框架 Laravel 框架不同的是,全部的 Lumen 框架的配置信息都存儲在 .env 文件中。一旦 Lumen 成功安裝,你須要 配置本地環境,若是沒有在目錄下新建.env文件web
APP_ENV=
local
APP_DEBUG=
true
APP_KEY=SomeRandomString!!!
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=lumen
DB_USERNAME=root
DB_PASSWORD=charlie
CACHE_DRIVER=memcached
QUEUE_DRIVER=sync
APP_TIMEZONE=PRC
DB_TIMEZONE=+08:00
|
php artisan make:migration create_users_table --create=users
|
執行這條命令後,會在項目目錄lumen/database/migrations/ 目錄下生成一個php文件,這個文件主要包括兩個函數,在up()函數中根據你的需求定義數據庫字段。sql
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
*
@return void
*/
public function up()
{
Schema::create(
'users', function (Blueprint $table) {
$table->increments(
'id');
$table->string(
'username');
$table->string(
'password');
$table->string(
'email');
$table->string(
'api_token', 60)->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
*
@return void
*/
public function down()
{
Schema::dropIfExists(
'users');
}
}
|
執行命令,建立數據庫數據庫
php artisan migrate
|
若是你的項目文件夾lumen\app\文件夾下沒有User.php文件,那麼新建一個User.php文件,文件內容以下:api
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
/**
* The attributes that are mass assignable.
*
*
@var array
*/
protected $fillable = [
'username', 'email', 'password', 'api_token'
];
/**
* The attributes excluded from the model's JSON form.
*
*
@var array
*/
protected $hidden = [
'password',
];
}
|
定義三個路由,實現用戶登陸,註冊及獲取用戶信息app
路由類型 | 路由路徑 | 路由控制器 |
---|---|---|
POST | user/register | UserController@register |
POST | user/login | UserController@login |
GET | user/info | UserController@info |
根據上述表的內容,在routes/web.php中定義路由composer
$app->get(
'/', function () use ($app) {
return $app->version();
});
//登陸註冊
$app->post(
'user/login', 'UserController@login');
$app->post(
'user/register', 'UserController@register');
$app->get(
'user/info', [
'middleware' => 'authToken',
'uses' => 'UserController@info'
]);
|
在Lumen\app\Http\Controllers\文件夾下新建用戶控制器UserController.php,實現用戶註冊、登陸和用戶信息獲取功能
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
private $salt;
public function __construct()
{
$this->salt = "userloginregister";
}
//登陸
public function login(Request $request)
{
if($request->has('username') && $request->has('password')){
$user = User::where(
'username', '=', $request->input('username'))->where('password', '=', sha1($this->salt.$request->input('password')))->first();
if($user){
$token = str_random(
60);
$user->api_token = $token;
$user->save();
return $user->api_token;
}
else{
return '用戶名或密碼不正確,登陸失敗';
}
}
else{
return '登陸信息不完整,請輸入用戶名和密碼';
}
}
//註冊
public function register(Request $request)
{
if($request->has('username') && $request->has('password') && $request->has('email')){
$user =
new User;
$user->username = $request->input(
'username');
$user->password = sha1(
$this->salt.$request->input('password'));
$user->email = $request->input(
'email');
$user->api_token = str_random(
60);
if($user->save()){
return '用戶註冊成功!';
}
else{
return '用戶註冊失敗!';
}
}
else{
return '請輸入完整用戶信息!';
}
}
//信息
public function info()
{
return Auth::user();
}
|
必需要經過token驗證才能獲取用戶信息。在Lumen\app\Http\Providers\AuthServiceProvider.php中定義驗證服務。咱們使用header包含token的形式來驗證。修改Lumen\app\Http\Providers\AuthServiceProvider.php文件代碼。
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
*
@return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
*
@return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->header('api_token')) {
return User::where('api_token', '=', $request->header('api_token'))->first();
}
});
}
|
在Lumen\app\Http\Middleware\文件夾下定義認證路由中間件AuthToken.php,就是以前在路由中定義的」authToken」。
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AuthToken
{
public function handle($request, Closure $next)
{
if(Auth::check()){
return $next($request);
}
else{
abort(
401);
}
}
}
|
在lumen\app\bootstrap\app.php中取消註釋
//讓數據庫信息和認證服務修改生效
$app->withFacades();
$app->withEloquent();
//認證中間件
$app->routeMiddleware([
'authToken' => App\Http\Middleware\AuthToken::class
]);
//開啓註冊提供者
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
|
php -S localhost:8000
|
1.
[Symfony\Component\Debug\Exception\FatalErrorException]
Class
'Memcached' not found
|
解決辦法,安裝memcached 和php擴展
brew install memcached
brew install php56-memcached
啓動memcached
memcached -D
|
2.
PHP Fatal error: Call to a member
function connection() on null in /Users/03315/www/lumen/vendor/illuminate/database/Eloquent/Model.php on line 1013
|
解決辦法,須要開啓,路徑app/bootstrap/app.php