Làm chủ Claude Code trong một tuần (Phần 3): Memory với CLAUDE.md
Đây là phần thứ ba trong series "Làm chủ Claude Code trong một tuần". Trong bài này, chúng ta sẽ tìm hiểu Memory — cách sử dụng CLAUDE.md để định nghĩa project conventions và context được tự động load.
Memory là gì?
Memory trong Claude Code là persistent context được lưu trữ trong các file CLAUDE.md. Không giống Slash Commands (chỉ session), Memory được tự động load mỗi khi bạn bắt đầu làm việc với Claude.
┌──────────────────────────────────────────────────────────────┐
│ MEMORY HIERARCHY │
├──────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────┐ │
│ │ ~/.claude/CLAUDE.md │ ◄── Personal (global preferences) │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ ./CLAUDE.md │ ◄── Project (team standards) │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ ./src/api/CLAUDE.md │ ◄── Directory (specific rules) │
│ └─────────────────────┘ │
│ │
│ Load order: Personal → Project → Directory │
│ (Later files can override earlier settings) │
│ │
└──────────────────────────────────────────────────────────────┘
Đặc điểm chính
| Tiêu chí | Giá trị |
|---|---|
| Cách gọi | Auto-loaded |
| Persistence | Cross-session |
| Vị trí file | Xem hierarchy ở trên |
| Format | Markdown (.md) |
| Dùng cho | Long-term learning, team standards |
Ba loại Memory
1. Personal Memory (Global)
Vị trí: ~/.claude/CLAUDE.md
Áp dụng cho tất cả dự án. Lưu trữ preferences cá nhân.
# Personal Claude Preferences
## Communication Style
- Respond in Vietnamese when asked in Vietnamese
- Use concise explanations
- Include code examples for concepts
## Coding Preferences
- Prefer functional programming patterns when appropriate
- Always include type hints in Python
- Use early returns to reduce nesting
## Tools & Frameworks
- Primary languages: PHP, TypeScript, Python
- Frameworks: Laravel, React, FastAPI
- Testing: PHPUnit, Jest, pytest
## Don't Do
- Don't explain basic concepts unless asked
- Don't add unnecessary comments in code
- Don't use deprecated methods/APIs
2. Project Memory
Vị trí: ./CLAUDE.md (root của project)
Áp dụng cho dự án hiện tại. Định nghĩa team standards.
# Project: E-Commerce Platform
## Overview
A Laravel-based e-commerce platform with React frontend.
## Tech Stack
- Backend: Laravel 11, PHP 8.3
- Frontend: React 18, TypeScript
- Database: PostgreSQL 16
- Cache: Redis 7
- Queue: Laravel Horizon
## Architecture
### Backend Structure
app/ ├── Actions/ # Single-purpose action classes ├── Http/ │ ├── Controllers/ # Thin controllers (max 5 methods) │ ├── Requests/ # Form validation │ └── Resources/ # API transformers ├── Models/ # Eloquent models ├── Services/ # Business logic └── Repositories/ # Data access layer
### Frontend Structure
src/ ├── components/ # Reusable UI components ├── features/ # Feature-based modules ├── hooks/ # Custom React hooks ├── services/ # API clients └── utils/ # Helper functions
## Coding Standards
### PHP
- PSR-12 coding style
- Strict types declaration required
- Use Laravel Pint for formatting
- Maximum function length: 20 lines
### TypeScript
- Strict mode enabled
- Use interfaces over types when possible
- Prefer functional components
- Use React Query for data fetching
### Git Conventions
- Branch naming: `feature/`, `bugfix/`, `hotfix/`
- Commit message format: `type(scope): description`
- PR must pass all CI checks
- Require 1 approval minimum
## Testing Requirements
- Minimum 80% coverage for new code
- Unit tests for all services
- Feature tests for API endpoints
- E2E tests for critical user flows
## API Conventions
- RESTful resource naming
- Use JSON:API specification
- Include pagination for list endpoints
- Return meaningful error messages
## Do's
- Use repository pattern for database queries
- Create form requests for validation
- Use resources for API responses
- Write feature tests for controllers
## Don'ts
- Don't use query builder in controllers
- Don't put business logic in models
- Don't use raw SQL unless necessary
- Don't skip validation
3. Directory Memory
Vị trí: ./path/to/directory/CLAUDE.md
Áp dụng cho thư mục cụ thể. Định nghĩa rules riêng.
Ví dụ: ./src/api/CLAUDE.md
# API Directory Rules
## Purpose
This directory contains all REST API endpoints.
## Conventions
### Controller Structure
```php
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
final class UserController extends Controller
{
public function __construct(
private readonly UserService $userService,
) {}
public function index(): AnonymousResourceCollection
{
return UserResource::collection(
$this->userService->paginate()
);
}
}
Response Format
All responses must follow JSON:API spec:
{
"data": [...],
"meta": {
"current_page": 1,
"total": 100
},
"links": {
"first": "...",
"last": "..."
}
}
Error Handling
{
"errors": [
{
"status": "422",
"title": "Validation Error",
"detail": "The email field is required."
}
]
}
Versioning
- Current version: v1
- Version in URL:
/api/v1/resources - Breaking changes require new version
Rate Limiting
- Default: 60 requests per minute
- Authenticated: 120 requests per minute
- Heavy endpoints: 10 requests per minute
## Cài đặt Memory
### Từ claude-howto
```bash
# Project memory
cp claude-howto/02-memory/project-CLAUDE.md ./CLAUDE.md
# Directory memory (ví dụ cho API)
cp claude-howto/02-memory/directory-api-CLAUDE.md ./src/api/CLAUDE.md
# Personal memory
cp claude-howto/02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md
Tự tạo
# Tạo project memory
touch CLAUDE.md
# Tạo directory memory
mkdir -p src/api
touch src/api/CLAUDE.md
# Tạo personal memory
mkdir -p ~/.claude
touch ~/.claude/CLAUDE.md
Cấu trúc CLAUDE.md hiệu quả
Template cơ bản
# Project Name
## Overview
Brief description of the project.
## Tech Stack
- Language/Framework versions
- Key dependencies
- Infrastructure
## Architecture
How the code is organized.
## Coding Standards
- Style guides
- Naming conventions
- Best practices
## Do's
List of encouraged practices.
## Don'ts
List of discouraged practices.
## Common Patterns
Frequently used patterns in this project.
## Resources
Links to relevant documentation.
Sections quan trọng
1. Overview
## Overview
A real-time collaboration platform built with Laravel and WebSockets.
Supports document editing, chat, and video calls.
Target users: Remote development teams (10-100 members).
2. Tech Stack với versions
## Tech Stack
| Category | Technology | Version |
|----------|------------|---------|
| Backend | Laravel | 11.x |
| Frontend | Vue.js | 3.4 |
| Database | PostgreSQL | 16 |
| Cache | Redis | 7.2 |
| Search | Meilisearch | 1.6 |
3. File naming conventions
## File Naming
### PHP Classes
- Controllers: `UserController.php` (singular + Controller)
- Models: `User.php` (singular)
- Services: `UserService.php` (singular + Service)
- Actions: `CreateUserAction.php` (verb + noun + Action)
### TypeScript
- Components: `UserCard.tsx` (PascalCase)
- Hooks: `useUser.ts` (camelCase with use prefix)
- Utils: `formatDate.ts` (camelCase)
4. Code examples
## Code Examples
### Service Pattern
```php
final class CreateUserAction
{
public function __construct(
private readonly UserRepository $users,
private readonly Hasher $hasher,
) {}
public function execute(array $data): User
{
return $this->users->create([
'name' => $data['name'],
'email' => $data['email'],
'password' => $this->hasher->make($data['password']),
]);
}
}
#### 5. Clear Do's and Don'ts
```markdown
## Do's
- ✅ Use dependency injection
- ✅ Write unit tests for services
- ✅ Use typed properties
- ✅ Return early to avoid nesting
## Don'ts
- ❌ Don't use static methods for business logic
- ❌ Don't put queries in controllers
- ❌ Don't use `dd()` in commits
- ❌ Don't hardcode configuration values
Memory Best Practices
1. Keep it DRY
Đừng lặp lại thông tin. Nếu đã định nghĩa ở project level, không cần lặp lại ở directory level.
2. Be Specific
# ❌ Bad
Use good coding practices.
# ✅ Good
- Maximum function length: 20 lines
- Maximum file length: 200 lines
- Maximum parameters: 4
- Use early returns instead of nested if-else
3. Include Examples
# ❌ Bad
Use the repository pattern.
# ✅ Good
Use the repository pattern:
```php
// In Controller
public function index(UserRepository $users)
{
return UserResource::collection($users->paginate());
}
// In Repository
final class UserRepository
{
public function paginate(int $perPage = 15): LengthAwarePaginator
{
return User::query()
->with(['roles', 'team'])
->latest()
->paginate($perPage);
}
}
### 4. Update regularly
Memory không phải "set and forget". Cập nhật khi:
- Thêm technology mới
- Thay đổi conventions
- Team đồng ý practices mới
- Phát hiện patterns không hiệu quả
### 5. Version control
Commit CLAUDE.md vào git để team sync:
```bash
git add CLAUDE.md
git commit -m "docs: update Claude Code memory with new API conventions"
Debugging Memory
Kiểm tra Memory được load
Trong Claude Code, hỏi:
What coding standards are defined in my project memory?
Memory không được áp dụng?
-
Kiểm tra vị trí file
ls -la CLAUDE.md ls -la ~/.claude/CLAUDE.md -
Kiểm tra nội dung
- Sử dụng headings rõ ràng (
##) - Không có syntax errors trong code blocks
- File không quá lớn (< 50KB recommended)
- Sử dụng headings rõ ràng (
-
Restart session Memory được load khi bắt đầu session mới.
Memory vs Slash Commands
| Aspect | Memory | Slash Commands |
|---|---|---|
| Loaded | Automatically | On demand (/cmd) |
| Scope | Context & rules | Specific actions |
| Persistence | Cross-session | Session only |
| Use case | Standards, conventions | Tasks, shortcuts |
Kết hợp cả hai:
- Memory: Định nghĩa coding standards
- Slash Commands: Tạo code theo standards đã định nghĩa
# Trong CLAUDE.md
## API Response Format
All API responses must use JSON:API specification.
# Trong /generate-api
Create API endpoint following the response format
defined in CLAUDE.md.
Ví dụ thực tế: Laravel Project Memory
# Laravel E-Commerce Project
## Tech Stack
- Laravel 11.x with PHP 8.3
- PostgreSQL 16 for database
- Redis 7 for cache and queues
- Meilisearch for product search
- Stripe for payments
## Directory Structure This Project Uses
app/ ├── Actions/ # Single-action classes │ ├── Cart/ │ ├── Order/ │ └── User/ ├── Http/ │ ├── Controllers/Api/ # API controllers (thin) │ ├── Controllers/Web/ # Web controllers (thin) │ ├── Requests/ # Form requests │ └── Resources/ # API resources ├── Models/ # Eloquent models ├── Repositories/ # Data access ├── Services/ # Complex business logic └── ValueObjects/ # Immutable value objects
## Patterns Used
### Action Pattern for Single Operations
```php
final class CreateOrderAction
{
public function execute(Cart $cart, User $user): Order
{
// Single responsibility
}
}
Repository for Data Access
interface OrderRepositoryInterface
{
public function findById(int $id): ?Order;
public function findByUser(User $user): Collection;
public function create(array $data): Order;
}
Value Objects for Domain Concepts
final readonly class Money
{
public function __construct(
public int $amount, // In cents
public string $currency,
) {}
}
Rules
Controllers
- Maximum 5 public methods
- Use constructor injection
- Return Resources for API
- Return Views for Web
- No business logic
Models
- Define fillable explicitly
- Use casts for types
- Keep relationships clean
- No query scopes over 3
- Observers for side effects
Services
- Interface required
- Constructor injection
- Throw domain exceptions
- Return DTOs or Models
Testing
Coverage Requirements
- Services: 90%
- Actions: 90%
- Controllers: 80%
- Models: 70%
Naming Convention
public function test_user_can_create_order(): void
{
// Arrange → Act → Assert
}
Do's
- ✅ Use actions for write operations
- ✅ Use repositories for read operations
- ✅ Create form requests for validation
- ✅ Use events for side effects
- ✅ Write factories for all models
Don'ts
- ❌ No Eloquent queries in controllers
- ❌ No business logic in models
- ❌ No hardcoded prices/config
- ❌ No
dd()ordump()in commits - ❌ No
@varwithout types
## Tổng kết
Memory là nền tảng để Claude Code hiểu project của bạn:
- ✅ Auto-loaded mỗi session
- ✅ Định nghĩa team standards rõ ràng
- ✅ Hierarchical (Personal → Project → Directory)
- ✅ Version controlled với git
## Tiếp theo
Trong phần tiếp theo, chúng ta sẽ tìm hiểu **Checkpoints** — cách lưu và khôi phục trạng thái session để thử nghiệm an toàn.
## Tài liệu tham khảo
- [Memory - claude-howto](https://github.com/luongnv89/claude-howto/tree/main/02-memory)
- [CLAUDE.md Best Practices](https://code.claude.com/docs/en/memory)
---
**Series này được dịch và mở rộng từ [claude-howto](https://github.com/luongnv89/claude-howto/) — MIT License.**