Helo! Dalam tutorial ini, kami akan membina API REST lengkap dalam Laravel untuk mengurus tugas. Saya akan membimbing anda melalui langkah asas, daripada menyediakan projek kepada membuat ujian automatik.
Buat projek Laravel baharu:
composer create-project laravel/laravel task-api cd task-api code .
Konfigurasikan pangkalan data:
Dalam fail .env, tetapkan konfigurasi pangkalan data anda:
DB_DATABASE=task_api DB_USERNAME=your_username DB_PASSWORD=your_password
Jana jadual tugas:
Jalankan arahan untuk mencipta migrasi baharu untuk jadual tugas:
php artisan make:migration create_tasks_table --create=tasks
Dalam fail migrasi (pangkalan data/migrasi/xxxx_xx_xx_create_tasks_table.php), tentukan struktur jadual:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('tasks', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('description')->nullable(); $table->boolean('completed')->default(false); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('tasks'); } };
Jalankan migrasi untuk mencipta jadual:
php artisan migrate
Buat model dan pengawal untuk tugas:
php artisan make:model Task php artisan make:controller TaskController --api
Tentukan model Tugas (app/Models/Task.php):
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Task extends Model { use HasFactory; protected $fillable = ['title', 'description', 'completed']; }
Dalam fail route/api.php, tambah laluan untuk TaskController:
<?php use App\Http\Controllers\TaskController; use Illuminate\Support\Facades\Route; Route::apiResource('tasks', TaskController::class);
Dalam TaskController, kami akan melaksanakan kaedah CRUD asas.
<?php namespace App\Http\Controllers; use App\Models\Task; use Illuminate\Http\Request; class TaskController extends Controller { public function index() { $tasks = Task::all(); return response()->json($tasks, 200); } public function store(Request $request) { $request->validate([ 'title' => 'required|string|max:255', 'description' => 'nullable|string' ]); $task = Task::create($request->all()); return response()->json($task, 201); } public function show(Task $task) { return response()->json($task, 200); } public function update(Request $request, Task $task) { $request->validate([ 'title' => 'required|string|max:255', 'description' => 'nullable|string', 'completed' => 'boolean' ]); $task->update($request->all()); return response()->json($task, 201); } public function destroy(Task $task) { $task->delete(); return response()->json(null, 204); } }
Kini kami akan menguji setiap titik akhir secara manual, menggunakan sambungan Kod VS yang dipanggil REST Client (https://marketplace.visualstudio.com/items?itemName=humao.rest-client). Jika anda mahu, anda juga boleh menggunakan Insomnia atau Posmen!
Selepas memasang sambungan, buat fail .http dalam folder projek anda dengan kandungan berikut:
### Create New Task POST http://127.0.0.1:8000/api/tasks HTTP/1.1 content-type: application/json Accept: application/json { "title": "Study Laravel" } ### Show Tasks GET http://127.0.0.1:8000/api/tasks HTTP/1.1 content-type: application/json Accept: application/json ### Show Task GET http://127.0.0.1:8000/api/tasks/1 HTTP/1.1 content-type: application/json Accept: application/json ### Update Task PUT http://127.0.0.1:8000/api/tasks/1 HTTP/1.1 content-type: application/json Accept: application/json { "title": "Study Laravel and Docker", "description": "We are studying!", "completed": false } ### Delete Task DELETE http://127.0.0.1:8000/api/tasks/1 HTTP/1.1 content-type: application/json Accept: application/json
Fail ini membolehkan anda menghantar permintaan terus daripada VS Code menggunakan sambungan REST Client, menjadikannya mudah untuk menguji setiap laluan dalam API anda.
Seterusnya, mari buat ujian untuk memastikan setiap laluan berfungsi seperti yang diharapkan.
Mula-mula, buat kilang untuk model Tugas:
php artisan make:factory TaskFactory
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; class TaskFactory extends Factory { public function definition(): array { return [ 'title' => fake()->sentence(), 'description' => fake()->paragraph(), 'completed' => false, ]; } }
Konfigurasi PHPUnit:
<?xml version="1.0" encoding="UTF-8"?> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true" > <testsuites> <testsuite name="Unit"> <directory>tests/Unit</directory> </testsuite> <testsuite name="Feature"> <directory>tests/Feature</directory> </testsuite> </testsuites> <source> <include> <directory>app</directory> </include> </source> <php> <env name="APP_ENV" value="testing" /> <env name="BCRYPT_ROUNDS" value="4" /> <env name="CACHE_DRIVER" value="array" /> <env name="DB_CONNECTION" value="sqlite" /> <env name="DB_DATABASE" value=":memory:" /> <env name="MAIL_MAILER" value="array" /> <env name="PULSE_ENABLED" value="false" /> <env name="QUEUE_CONNECTION" value="sync" /> <env name="SESSION_DRIVER" value="array" /> <env name="TELESCOPE_ENABLED" value="false" /> </php> </phpunit>
Buat ujian penyepaduan:
php artisan make:test TaskApiTest
Dalam fail tests/Feature/TaskApiTest.php, laksanakan ujian:
<?php namespace Tests\Feature; use App\Models\Task; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class TaskApiTest extends TestCase { use RefreshDatabase; public function test_can_create_task(): void { $response = $this->postJson('/api/tasks', [ 'title' => 'New Task', 'description' => 'Task Description', 'completed' => false, ]); $response->assertStatus(201); $response->assertJson([ 'title' => 'New Task', 'description' => 'Task Description', 'completed' => false, ]); } public function test_can_list_tasks() { Task::factory()->count(3)->create(); $response = $this->getJson('/api/tasks'); $response->assertStatus(200); $response->assertJsonCount(3); } public function test_can_show_task() { $task = Task::factory()->create(); $response = $this->getJson("/api/tasks/{$task->id}"); $response->assertStatus(200); $response->assertJson([ 'title' => $task->title, 'description' => $task->description, 'completed' => false, ]); } public function test_can_update_task() { $task = Task::factory()->create(); $response = $this->putJson("/api/tasks/{$task->id}", [ 'title' => 'Update Task', 'description' => 'Update Description', 'completed' => true, ]); $response->assertStatus(201); $response->assertJson([ 'title' => 'Update Task', 'description' => 'Update Description', 'completed' => true, ]); } public function test_can_delete_task() { $task = Task::factory()->create(); $response = $this->deleteJson("/api/tasks/{$task->id}"); $response->assertStatus(204); $this->assertDatabaseMissing('tasks', ['id' => $task->id]); } }
Jalankan ujian:
php artisan test
*Terima kasih! *
Atas ialah kandungan terperinci Cara Membuat API REST Menggunakan Laravel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!