使用Laravel编写Api实现push用户数据
2018年6月10日17:56:39 实习第六周 XXM
Begin
首先我们需要在api.php文件中定义一条Api路由.
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('/pushUser','pushDataController@test');
Route::post('/pushUser','pushDataController@importUser');
然后通过artisan命令创建一个Controller
php artisan make:controller pushDataController
创建后,我们定义一个importUser方法来为对数据进行操作.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class pushDataController extends Controller
{
public function importUser(Request $request)
{
//获取传过来的数据
$json = $request->data;
//对Json 解码
$json =json_decode($json,true);
$user = User::firstOrNew([
'UserAccount'=>$json['UserAccount'],
]);
//批量填入
$user->fill($json);
$user->save();
}
public function test()
{
return 123;
}
}
完成以上操作,就成功地实现了一个简单的Api.
然后我们便需要一个方法来为Api提供数据.
我们需要生成一个command
php artisan make:command PushUser
然后为PushUser完善代码
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\User;
use GuzzleHttp\Client;
class PushUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'push:blogUser {--user} {--take=} {--api=}';
/**
* The console command description.
*
* @var string
*/
protected $description = ' push blogUser data';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->client = new Client();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if($this->option('user'))
{
$this->push_user();
}
}
public function push_user()
{
if(!$this->option('take')&&!$this->option('api'))
{
$this->error('take Or api not found');
return;
}
$take=$this->option('take');
$api=$this->option('api');
$users=User::orderBy('Id')->take($take)->get();
foreach ($users as $user) {
$json = json_encode([
'UserAccount'=>$user->UserAccount,
'UserPass'=>$user->UserPass,
],JSON_UNESCAPED_UNICODE);
$response = @$this->client->request(
'POST',
$api,
[
'form_params'=>[
'data'=>$json,
],
]
);
if(!$response)
{
$this->error('error server');
}
else
{
$this->info("$user->UserAccount success");
}
}
}
}
以上完成后我们便可以通过控制台来向目标Api Push数据了.
DB
End
这个人暂时没有 freestyle