-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy path.cursorrules
188 lines (179 loc) · 9.02 KB
/
.cursorrules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
You are an expert in Laravel, PHP. This project is my blog project.
- Always print logs, messages in English. This is a laravel package for English people.
- Write the code shorter, and less complex as much as possible. Don't need to do over-engineering.
## Laravel Debugging Best Practices
- Use the `dump()` function to inspect variable values without stopping execution:
```php
dump($variable); // Shows the value and continues execution
dump($user->profile, $settings); // Can dump multiple variables at once
```
- Use the `dd()` (dump and die) function to inspect values and halt execution at critical points:
```php
dd($variable); // Displays the value and stops execution completely
```
- For complex debugging, use strategic placement of dump/dd calls:
```php
// Place before suspected problem areas
dump('Checkpoint 1', $data);
// Complex logic here
dump('Checkpoint 2', $data); // See how data changed
```
- Use the Laravel Debug Bar package for advanced debugging:
```bash
composer require barryvdh/laravel-debugbar --dev
```
- For API debugging, use `Log::debug()` to record values without affecting the response:
```php
Log::debug('API Request', ['data' => $request->all()]);
```
- In loops or collections, use the `tap()` helper to debug without breaking chains:
```php
$collection->map(function ($item) {
return tap($item->process(), function ($processed) use ($item) {
dump("Processing item {$item->id}", $processed);
});
});
```
## Command-line Debugging in Laravel
- Use Artisan Tinker for interactive debugging:
```bash
php artisan tinker
>>> App\Models\User::find(1) // Test queries directly
>>> DB::table('users')->where('email', 'test@example.com')->first() // Check data
```
- Check Laravel logs for errors:
```bash
tail -f storage/logs/laravel.log
```
- Use Artisan to clear caches when experiencing unexpected behavior:
```bash
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
```
- Debug failing tests with verbose output:
```bash
php artisan test --filter=TestName -v
```
- Run a specific piece of code for testing:
```bash
php artisan tinker
>>> require app_path('path/to/your/file.php');
>>> $result = (new SomeClass())->methodToTest('test');
>>> dump($result);
```
- Check route list to verify routes are registered correctly:
```bash
php artisan route:list --method=GET
```
- Test queue jobs explicitly:
```bash
php artisan queue:work --once
```
- Analyze database queries with query counting:
```php
DB::enableQueryLog();
// Code with queries here
dd(DB::getQueryLog());
```
## Cursor Best Practice for Debugging
## PHP/Laravel
- This project strictly uses PHP 8.1. You MUST utilize all PHP 8.1 features for optimal and concise code. Features from PHP 8.2 and above are STRICTLY PROHIBITED:
- Required PHP 8.0 & 8.1 Features (USE THESE):
- **Match Expression**: Always prefer match over switch. Example: `match($status) { 200 => 'OK', 404 => 'Not Found', default => 'Unknown' };`
- **Named Arguments**: Use for better readability. Example: `function greet(string $name, int $age) { ... } greet(age: 30, name: 'Alice');`
- **Union Types**: Always use for flexible typing. Example: `function process(int|float $value): int|float { return $value * 2; }`
- **Constructor Property Promotion**: Required for all new classes. Example: `class User { public function __construct(private string $name, private int $age) {} }`
- **Attributes**: Use for metadata. Example: `#[ExampleAttribute] class MyClass { ... }`
- **Nullsafe Operator**: Required for all nullable chains. Example: `$username = $user?->getProfile()?->getUsername();`
- **String Functions**: Always use new string functions. Example: `str_contains()`, `str_starts_with()`, `str_ends_with()`
- **Enums**: Define custom types with fixed values. Example: `enum Status { case PENDING; case APPROVED; case REJECTED; } $currentStatus = Status::PENDING;`
- **Readonly Properties**: Properties that can only be written once. Example: `class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } }`
- **Intersection Types**: Require multiple types at once. Example: `interface A {} interface B {} function test(A&B $obj) { /* ... */ }`
- **`never` Return Type**: For functions that never return. Example: `function stop(): never { exit(); }`
- **`new` in Initializers**: Use `new` directly in property defaults. Example: `class Service { public object $logger; public function __construct(object $logger = new Logger()) { $this->logger = $logger; } }`
- PROHIBITED Features (DO NOT USE):
- PHP 8.1: Enums, Readonly Properties, First-class Callable Syntax, Pure Intersection Types, Never Return Type
- PHP 8.2: Readonly Classes, DNF Types, Null/False Standalone Types
- PHP 8.3: Typed Class Constants, #[\Override], Anonymous readonly classes
- Follow PSR-12 coding standards.
- Utilize Laravel's built-in features and helpers when possible.
- File structure: Follow Laravel's directory structure and naming conventions.
- Implement proper error handling and logging:
- Use Laravel's exception handling and logging features.
- Create custom exceptions when necessary.
- Use try-catch blocks for expected exceptions.
- Use Laravel's validation features for form and request validation.
- Implement middleware for request filtering and modification.
- Utilize Laravel's Eloquent ORM for database interactions.
- Use Laravel's query builder for complex database queries.
- Implement proper database migrations and seeders.
- Don't need to use interface for single implementation.
- Always define route names for each route. Use that on everywhere including inertia (tsx) links.
- For better performance in database, don't create foreign key relations. But consider creating indexes for columns that are frequently used in where clauses.
- I hate sprintf(). Please use "{$variable}" (not ${variable}) for string interpolation.
- When you make new migration file, use `php artisan make:migration create_table_name_table` command first before ccoding the Schema.
- When you code scheduled task, use the file 'console.php' instead of 'Kernel.php'.
- Never put two classes in a single file. Every php files should be only one single class.
- When creating classes and methods, always add comments describing their purpose and objectives. For method implementations, only add comments when:
- The code logic is complex or not immediately obvious
- There are important business rules or constraints that need to be documented
- The implementation requires specific context or background information
- There are performance considerations or edge cases to be aware of
- Never use numbered lists (1. 2. 3. 4.) in comments.
Example:
```php
/**
* Purpose: Handles user authentication and authorization
* Objectives:
* - Manage user login/logout process
* - Handle session management
* - Implement role-based access control
*/
class AuthenticationService {
/**
* Complex business logic that requires explanation
* - Implements special rate limiting rules based on user type
* - Handles legacy authentication methods for backward compatibility
* - Uses exponential backoff for failed attempts
*/
public function complexAuthenticationLogic(): bool {
// Code here needs comments due to complexity
}
// Simple methods with clear implementation don't need comments
public function logout(): void {
$this->guard->logout();
session()->invalidate();
}
}
```
Dependencies
- Laravel 10
- Composer for dependency management
Laravel Best Practices
- Use Eloquent ORM instead of raw SQL queries when possible.
- Implement Repository pattern for data access layer.
- Use Laravel's built-in authentication and authorization features.
- Utilize Laravel's caching mechanisms for improved performance.
- Implement job queues for long-running tasks.
- Use Laravel's built-in testing tools (PHPUnit, Dusk) for unit and feature tests.
- Implement API versioning for public APIs.
- Use Laravel's localization features for multi-language support.
- Implement proper CSRF protection and security measures.
- Use Laravel Mix for asset compilation.
- Implement proper database indexing for improved query performance.
- Use Laravel's built-in pagination features.
- Implement proper error logging and monitoring.
- Locate All API routes in api.php file.
Key Conventions
1. Follow Laravel's MVC architecture.
2. Use Laravel's routing system for defining application endpoints.
3. Implement proper request validation using Form Requests.
4. Use Laravel's Blade templating engine for views.
5. Implement proper database relationships using Eloquent.
6. Use Laravel's built-in authentication scaffolding.
7. Implement proper API resource transformations.
8. Use Laravel's event and listener system for decoupled code.
9. Implement proper database transactions for data integrity.
10. Use Laravel's built-in scheduling features for recurring tasks.