getting-started.md

13.34 KB
01/10/2025 12:35
MD
getting-started.md
# เริ่มต้นใช้งาน Kotchasan Framework

## การสร้างโปรเจ็คใหม่

### 1. สร้างโปรเจ็ค

```bash
# สร้างโปรเจ็คใหม่
composer create-project kotchasan/framework my-app

# เข้าไปในโฟลเดอร์โปรเจ็ค
cd my-app
```

### 2. ตั้งค่า Environment

```bash
# คัดลอกไฟล์ environment
cp .env.example .env

# สร้าง application key
php artisan key:generate
```

### 3. ตั้งค่าฐานข้อมูล

```bash
# รัน migration
php artisan migrate

# Seed ข้อมูลเริ่มต้น
php artisan db:seed
```

## โครงสร้างโปรเจ็ค

```
my-app/
├── app/
│   ├── Controllers/     # Controllers
│   ├── Models/         # Models
│   ├── Middleware/     # Middleware
│   └── Services/       # Business Logic
├── config/             # Configuration files
├── database/
│   ├── migrations/     # Database migrations
│   └── seeders/        # Database seeders
├── public/             # Web root
├── resources/
│   ├── views/          # Blade templates
│   └── assets/         # CSS, JS, Images
├── routes/             # Route definitions
├── storage/            # Logs, cache, sessions
└── tests/              # Test files
```

## การสร้าง Controller

### 1. สร้าง Controller ใหม่

```bash
php artisan make:controller HomeController
```

### 2. เขียน Controller

```php
<?php
namespace App\Controllers;

use Kotchasan\Controller;
use Kotchasan\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        $data = [
            'title' => 'หน้าแรก',
            'message' => 'ยินดีต้อนรับสู่ Kotchasan Framework'
        ];

        return $this->view('home', $data);
    }

    public function about()
    {
        return $this->view('about', [
            'title' => 'เกี่ยวกับเรา'
        ]);
    }
}
```

## การสร้าง Model

### 1. สร้าง Model ใหม่

```bash
php artisan make:model User
```

### 2. เขียน Model

```php
<?php
namespace App\Models;

use Kotchasan\Model;

class User extends Model
{
    protected $table = 'users';

    protected $fillable = [
        'name', 'email', 'password'
    ];

    protected $hidden = [
        'password', 'remember_token'
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    // Relationships
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}
```

## การสร้าง View

### 1. สร้างไฟล์ View

```html
<!-- resources/views/home.blade.php -->
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $title ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1><?= $title ?></h1>
        <p><?= $message ?></p>

        <div class="row">
            <div class="col-md-6">
                <h2>คุณสมบัติ</h2>
                <ul>
                    <li>ประสิทธิภาพสูง</li>
                    <li>ความปลอดภัย</li>
                    <li>ใช้งานง่าย</li>
                </ul>
            </div>
            <div class="col-md-6">
                <h2>การใช้งาน</h2>
                <p>เริ่มต้นสร้างแอปพลิเคชันของคุณได้ทันที</p>
            </div>
        </div>
    </div>
</body>
</html>
```

### 2. Layout Template

```html
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $title ?? 'Kotchasan Framework' ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">Kotchasan</a>
            <div class="navbar-nav">
                <a class="nav-link" href="/">หน้าแรก</a>
                <a class="nav-link" href="/about">เกี่ยวกับ</a>
            </div>
        </div>
    </nav>

    <main class="container mt-4">
        <?= $content ?>
    </main>

    <footer class="bg-light text-center py-3 mt-5">
        <p>&copy; 2024 Kotchasan Framework</p>
    </footer>
</body>
</html>
```

## การตั้งค่า Routing

### 1. Web Routes

```php
<?php
// routes/web.php

use App\Controllers\HomeController;
use App\Controllers\PostController;

// หน้าแรก
Route::get('/', [HomeController::class, 'index']);

// เกี่ยวกับเรา
Route::get('/about', [HomeController::class, 'about']);

// Posts
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}', [PostController::class, 'show']);
Route::post('/posts', [PostController::class, 'store']);
```

### 2. API Routes

```php
<?php
// routes/api.php

use App\Controllers\Api\PostController;

Route::prefix('api')->group(function () {
    Route::get('/posts', [PostController::class, 'index']);
    Route::get('/posts/{id}', [PostController::class, 'show']);
    Route::post('/posts', [PostController::class, 'store']);
    Route::put('/posts/{id}', [PostController::class, 'update']);
    Route::delete('/posts/{id}', [PostController::class, 'destroy']);
});
```

## การทำงานกับฐานข้อมูล

### 1. Migration

```bash
# สร้าง migration
php artisan make:migration create_posts_table
```

```php
<?php
// database/migrations/xxxx_create_posts_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->unsignedBigInteger('user_id');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
};
```

### 2. Seeder

```bash
# สร้าง seeder
php artisan make:seeder PostSeeder
```

```php
<?php
// database/seeders/PostSeeder.php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Post;
use App\Models\User;

class PostSeeder extends Seeder
{
    public function run()
    {
        $user = User::first();

        Post::create([
            'title' => 'โพสต์แรก',
            'content' => 'เนื้อหาของโพสต์แรก',
            'user_id' => $user->id
        ]);
    }
}
```

## การใช้ Form และ Validation

### 1. สร้าง Form

```html
<!-- resources/views/posts/create.blade.php -->
<form method="POST" action="/posts">
    <?= csrf_token() ?>

    <div class="mb-3">
        <label for="title" class="form-label">หัวข้อ</label>
        <input type="text" class="form-control" id="title" name="title" required>
    </div>

    <div class="mb-3">
        <label for="content" class="form-label">เนื้อหา</label>
        <textarea class="form-control" id="content" name="content" rows="5" required></textarea>
    </div>

    <button type="submit" class="btn btn-primary">บันทึก</button>
</form>
```

### 2. Validation ใน Controller

```php
<?php
namespace App\Controllers;

use Kotchasan\Controller;
use Kotchasan\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function store(Request $request)
    {
        // Validation
        $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string'
        ]);

        // Create post
        $post = Post::create([
            'title' => $request->title,
            'content' => $request->content,
            'user_id' => auth()->id()
        ]);

        return redirect('/posts/' . $post->id);
    }
}
```

## การใช้ Middleware

### 1. สร้าง Middleware

```bash
php artisan make:middleware AuthMiddleware
```

```php
<?php
namespace App\Middleware;

use Kotchasan\Http\Request;
use Kotchasan\Http\Response;

class AuthMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        if (!auth()->check()) {
            return redirect('/login');
        }

        return $next($request);
    }
}
```

### 2. ลงทะเบียน Middleware

```php
<?php
// config/middleware.php

return [
    'auth' => \App\Middleware\AuthMiddleware::class,
    'guest' => \App\Middleware\GuestMiddleware::class,
];
```

### 3. ใช้ Middleware ใน Route

```php
<?php
// routes/web.php

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'index']);
});
```

## การใช้ Session และ Cookie

### 1. Session

```php
<?php
// เก็บข้อมูลใน session
session(['user_id' => $user->id]);
session(['cart' => $cartItems]);

// อ่านข้อมูลจาก session
$userId = session('user_id');
$cart = session('cart', []);

// ลบข้อมูลจาก session
session()->forget('cart');
```

### 2. Cookie

```php
<?php
// ตั้งค่า cookie
setcookie('theme', 'dark', time() + 3600, '/');

// อ่าน cookie
$theme = $_COOKIE['theme'] ?? 'light';
```

## การใช้ Cache

### 1. Cache ข้อมูล

```php
<?php
use Kotchasan\Cache\Cache;

// เก็บข้อมูลใน cache
Cache::put('users', $users, 3600); // 1 ชั่วโมง

// อ่านข้อมูลจาก cache
$users = Cache::get('users');

// ลบข้อมูลจาก cache
Cache::forget('users');
```

### 2. Cache Tags

```php
<?php
// ใช้ cache tags
Cache::tags(['posts', 'user-' . $userId])->put('user_posts', $posts, 3600);

// ลบ cache ตาม tags
Cache::tags(['posts'])->flush();
```

## การใช้ Queue

### 1. สร้าง Job

```bash
php artisan make:job SendEmailJob
```

```php
<?php
namespace App\Jobs;

use Kotchasan\Queue\Job;

class SendEmailJob extends Job
{
    protected $email;
    protected $subject;
    protected $message;

    public function __construct($email, $subject, $message)
    {
        $this->email = $email;
        $this->subject = $subject;
        $this->message = $message;
    }

    public function handle()
    {
        // ส่งอีเมล
        mail($this->email, $this->subject, $this->message);
    }
}
```

### 2. Dispatch Job

```php
<?php
// Dispatch job
SendEmailJob::dispatch($email, $subject, $message);

// หรือใช้ delay
SendEmailJob::dispatch($email, $subject, $message)->delay(now()->addMinutes(5));
```

## การทดสอบ

### 1. Unit Test

```php
<?php
namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use App\Models\User;

class UserTest extends TestCase
{
    public function testUserCreation()
    {
        $user = new User([
            'name' => 'John Doe',
            'email' => 'john@example.com'
        ]);

        $this->assertEquals('John Doe', $user->name);
        $this->assertEquals('john@example.com', $user->email);
    }
}
```

### 2. Feature Test

```php
<?php
namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;

class PostTest extends TestCase
{
    public function testCreatePost()
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)
            ->post('/posts', [
                'title' => 'Test Post',
                'content' => 'Test Content'
            ]);

        $response->assertStatus(302);
        $this->assertDatabaseHas('posts', [
            'title' => 'Test Post'
        ]);
    }
}
```

## การ Deploy

### 1. Production Setup

```bash
# ตั้งค่า environment
cp .env.example .env
# แก้ไข .env สำหรับ production

# Install dependencies
composer install --no-dev --optimize-autoloader

# Generate key
php artisan key:generate

# Run migrations
php artisan migrate --force

# Cache configuration
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### 2. Web Server Configuration

```nginx
server {
    listen 80;
    server_name your-domain.com;
    root /path/to/kotchasan/public;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}
```

---

**หมายเหตุ**: นี่คือคู่มือเริ่มต้นใช้งาน สำหรับข้อมูลเพิ่มเติมโปรดดูที่ [API Reference](api-reference.md)