# Getting Started with Kotchasan Framework
## Creating a New Project
### 1. Create Project
```bash
# Create new project
composer create-project kotchasan/framework my-app
# Navigate to project directory
cd my-app
```
### 2. Environment Setup
```bash
# Copy environment file
cp .env.example .env
# Generate application key
php artisan key:generate
```
### 3. Database Setup
```bash
# Run migrations
php artisan migrate
# Seed initial data
php artisan db:seed
```
## Project Structure
```
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
```
## Creating Controllers
### 1. Create New Controller
```bash
php artisan make:controller HomeController
```
### 2. Write Controller
```php
<?php
namespace App\Controllers;
use Kotchasan\Controller;
use Kotchasan\Http\Request;
class HomeController extends Controller
{
public function index(Request $request)
{
$data = [
'title' => 'Home Page',
'message' => 'Welcome to Kotchasan Framework'
];
return $this->view('home', $data);
}
public function about()
{
return $this->view('about', [
'title' => 'About Us'
]);
}
}
```
## Creating Models
### 1. Create New Model
```bash
php artisan make:model User
```
### 2. Write 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);
}
}
```
## Creating Views
### 1. Create View File
```html
<!-- resources/views/home.blade.php -->
<!DOCTYPE html>
<html lang="en">
<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>Features</h2>
<ul>
<li>High Performance</li>
<li>Security</li>
<li>Easy to Use</li>
</ul>
</div>
<div class="col-md-6">
<h2>Usage</h2>
<p>Start building your application right away</p>
</div>
</div>
</div>
</body>
</html>
```
### 2. Layout Template
```html
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="en">
<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="/">Home</a>
<a class="nav-link" href="/about">About</a>
</div>
</div>
</nav>
<main class="container mt-4">
<?= $content ?>
</main>
<footer class="bg-light text-center py-3 mt-5">
<p>© 2024 Kotchasan Framework</p>
</footer>
</body>
</html>
```
## Routing Configuration
### 1. Web Routes
```php
<?php
// routes/web.php
use App\Controllers\HomeController;
use App\Controllers\PostController;
// Home page
Route::get('/', [HomeController::class, 'index']);
// About page
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']);
});
```
## Working with Database
### 1. Migration
```bash
# Create 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
# Create 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' => 'First Post',
'content' => 'Content of the first post',
'user_id' => $user->id
]);
}
}
```
## Using Forms and Validation
### 1. Create 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">Title</label>
<input type="text" class="form-control" id="title" name="title" required>
</div>
<div class="mb-3">
<label for="content" class="form-label">Content</label>
<textarea class="form-control" id="content" name="content" rows="5" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
```
### 2. Validation in 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);
}
}
```
## Using Middleware
### 1. Create 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. Register Middleware
```php
<?php
// config/middleware.php
return [
'auth' => \App\Middleware\AuthMiddleware::class,
'guest' => \App\Middleware\GuestMiddleware::class,
];
```
### 3. Use Middleware in Routes
```php
<?php
// routes/web.php
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/profile', [ProfileController::class, 'index']);
});
```
## Using Sessions and Cookies
### 1. Session
```php
<?php
// Store data in session
session(['user_id' => $user->id]);
session(['cart' => $cartItems]);
// Read data from session
$userId = session('user_id');
$cart = session('cart', []);
// Remove data from session
session()->forget('cart');
```
### 2. Cookie
```php
<?php
// Set cookie
setcookie('theme', 'dark', time() + 3600, '/');
// Read cookie
$theme = $_COOKIE['theme'] ?? 'light';
```
## Using Cache
### 1. Cache Data
```php
<?php
use Kotchasan\Cache\Cache;
// Store data in cache
Cache::put('users', $users, 3600); // 1 hour
// Read data from cache
$users = Cache::get('users');
// Remove data from cache
Cache::forget('users');
```
### 2. Cache Tags
```php
<?php
// Use cache tags
Cache::tags(['posts', 'user-' . $userId])->put('user_posts', $posts, 3600);
// Remove cache by tags
Cache::tags(['posts'])->flush();
```
## Using Queue
### 1. Create 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()
{
// Send email
mail($this->email, $this->subject, $this->message);
}
}
```
### 2. Dispatch Job
```php
<?php
// Dispatch job
SendEmailJob::dispatch($email, $subject, $message);
// Or use delay
SendEmailJob::dispatch($email, $subject, $message)->delay(now()->addMinutes(5));
```
## Testing
### 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'
]);
}
}
```
## Deployment
### 1. Production Setup
```bash
# Environment setup
cp .env.example .env
# Edit .env for 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;
}
}
```
---
**Note**: This is a getting started guide. For more information, please refer to the [API Reference](api-reference.md)