Master Claude Code in a Week (Part 3): Memory with CLAUDE.md
This is the third part of the "Master Claude Code in a Week" series. In this article, we'll explore Memory — how to use CLAUDE.md to define project conventions and context that's automatically loaded.
What is Memory?
Memory in Claude Code is persistent context stored in CLAUDE.md files. Unlike Slash Commands (session only), Memory is automatically loaded every time you start working with 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) │
│ │
└──────────────────────────────────────────────────────────────┘
Key Characteristics
| Criteria | Value |
|---|---|
| Invocation | Auto-loaded |
| Persistence | Cross-session |
| File Location | See hierarchy above |
| Format | Markdown (.md) |
| Best For | Long-term learning, team standards |
Three Types of Memory
1. Personal Memory (Global)
Location: ~/.claude/CLAUDE.md
Applies to all projects. Stores personal preferences.
# Personal Claude Preferences
## Communication Style
- Respond in English by default
- 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
Location: ./CLAUDE.md (project root)
Applies to current project. Defines 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
Location: ./path/to/directory/CLAUDE.md
Applies to specific directory. Defines specific rules.
Example: ./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
## Installing Memory
### From claude-howto
```bash
# Project memory
cp claude-howto/02-memory/project-CLAUDE.md ./CLAUDE.md
# Directory memory (example for 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
Create your own
# Create project memory
touch CLAUDE.md
# Create directory memory
mkdir -p src/api
touch src/api/CLAUDE.md
# Create personal memory
mkdir -p ~/.claude
touch ~/.claude/CLAUDE.md
Effective CLAUDE.md Structure
Basic Template
# 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.
Important Sections
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 with 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
Don't repeat information. If defined at project level, no need to repeat at 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 isn't "set and forget". Update when:
- Adding new technology
- Changing conventions
- Team agrees on new practices
- Discovering ineffective patterns
### 5. Version control
Commit CLAUDE.md to git for team sync:
```bash
git add CLAUDE.md
git commit -m "docs: update Claude Code memory with new API conventions"
Debugging Memory
Check if Memory is loaded
In Claude Code, ask:
What coding standards are defined in my project memory?
Memory not being applied?
-
Check file location
ls -la CLAUDE.md ls -la ~/.claude/CLAUDE.md -
Check content
- Use clear headings (
##) - No syntax errors in code blocks
- File not too large (< 50KB recommended)
- Use clear headings (
-
Restart session Memory is loaded when starting a new session.
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 |
Combine both:
- Memory: Define coding standards
- Slash Commands: Create code following defined standards
# In CLAUDE.md
## API Response Format
All API responses must use JSON:API specification.
# In /generate-api
Create API endpoint following the response format
defined in CLAUDE.md.
Summary
Memory is the foundation for Claude Code to understand your project:
- ✅ Auto-loaded every session
- ✅ Clear team standards definition
- ✅ Hierarchical (Personal → Project → Directory)
- ✅ Version controlled with git
Next Up
In the next part, we'll explore Checkpoints — how to save and restore session state for safe experimentation.
References
This series is translated and expanded from claude-howto — MIT License.