# AGENTS.md - CRMEB PRO Development Guide ## Project Overview CRMEB PRO is an e-commerce system based on ThinkPHP 8.0 + Swoole 4. PHP 8.0+ required. This document provides guidelines for agentic coding assistants working in this codebase. --- ## 1. Build/Lint/Test Commands ### Application Commands ```bash # Start Swoole server (main application command) php think swoole # Clear runtime files php think clear # Build route cache php think optimize:route # Build database schema cache php think optimize:schema ``` ### Code Generation ```bash # Generate controller php think make:controller api@user/User # Generate model php think make:model api@user/User # Generate service (app/services/) php think make:service api@user/User # Generate dao (app/dao/) php think make:dao api@user/User # Generate validate class php think make:validate api@user/User # Generate event php think make:event UserLogin # Generate listener php think make:listener UserLoginListener # Generate middleware php think make:middleware Auth ``` ### Queue Commands ```bash # Process queue jobs php think queue:work # Listen to queue php think queue:listen # Retry failed jobs php think queue:retry # List failed jobs php think queue:failed ``` ### Dependency Management ```bash # Install dependencies composer install # Update dependencies composer update # Dump autoload composer dump-autoload ``` --- ## 2. Code Style Guidelines ### PSR Standards - Follows **PSR-2** (Coding Style) and **PSR-4** (Autoloading) ### Naming Conventions | Element | Convention | Example | |---------|------------|---------| | Directory | lowercase + underscore | `app/controller/admin` | | File (.php) | CamelCase or lowercase_underscore | `UserController.php`, `common.php` | | Class/Interface/Trait | PascalCase | `BaseServices`, `UserDao` | | Method | camelCase | `getUserInfo()`, `createToken()` | | Property | camelCase | `$adminInfo`, `$page` | | Variable | camelCase | `$userId`, `$orderData` | | Constant | UPPER_SNAKE_CASE | `PASSWORD_BCRYPT`, `MAX_RETRY` | | Config param | lowercase + underscore | `url_route_on`, `cache.is_gzde` | | Table/Column | lowercase + underscore | `eb_user`, `user_name` | ### File Header Template ```php // +---------------------------------------------------------------------- namespace app\controller\admin; ``` ### PHP Syntax Rules 1. **Namespace/use blocks** - Insert blank line after use statements 2. **Braces** - Class/method braces on separate lines 3. **Access modifiers** - Required for all methods and properties (`private`, `protected`, `public`) 4. **Parameters** - Comma after each param, not before 5. **Control structures** - Space after keyword (`if (` not `if(`) 6. **Assignment** - Spaces around `=` (`$arr = []`) 7. **Closing tag** - Omit `?>` for pure PHP files 8. **PHP 8.0+ features** - Use nullsafe operator (`$obj?->method()`), named arguments, union types --- ## 3. Architecture Patterns ### Directory Structure ``` app/ ├── controller/ # Controllers (extend BaseController) │ ├── admin/ # Admin panel controllers │ ├── api/ # API controllers │ └── supplier/ # Supplier controllers ├── services/ # Business logic layer ├── dao/ # Data access layer ├── model/ # Database models ├── validate/ # Form validation classes ├── http/ │ └── middleware/ # Middleware classes └── jobs/ # Queue jobs crmeb/ ├── basic/ # Base classes (BaseController, BaseModel, BaseServices) ├── traits/ # Reusable traits ├── services/ # Core services ├── utils/ # Utility classes └── exceptions/ # Custom exception classes ``` ### Layer Pattern ``` Controller -> Service -> Dao -> Model ``` - **Controller**: Request handling, response formatting, auth checks - **Service**: Business logic, transaction management - **Dao**: Data query operations, search conditions - **Model**: Database operations via ORM ### Class Naming - Controllers: `{Name}Controller` (e.g., `StoreProductController`) - Services: `{Name}Services` (e.g., `StoreProductServices`) - DAOs: `{Name}Dao` (e.g., `StoreProductDao`) - Models: `{Name}` (e.g., `StoreProduct`) - Validates: `{Name}Validate` (e.g., `StoreProductValidate`) --- ## 4. Controller Guidelines ### Base Controller ```php use app\controller\admin\AuthController; // extends BaseController class ProductController extends AuthController { // Access $this->request via dependency injection public function index(Request $request): Response { // Use $this->success() / $this->fail() for JSON responses return $this->success(['list' => []]); } } ``` ### Request Data Retrieval ```php // Single parameter $id = $this->request->param('id'); // Multiple parameters with defaults [$page, $limit] = $this->request->more(['page/d', 'limit/d']); // With default values [$name, $status] = $this->request->more([ ['name', ''], ['status', 0] ], true); ``` --- ## 5. Service Guidelines ### BaseServices Pattern ```php namespace app\services\product; use app\services\BaseServices; class StoreProductServices extends BaseServices { // Inject dao via constructor or magic method __call public function getInfo(int $id) { return $this->dao->get($id); } } ``` ### Dao Injection Services access Dao via `$this->dao` property (injected via `ServicesTrait`). --- ## 6. Dao Guidelines ### BaseDao Pattern ```php namespace app\dao\product; use app\dao\BaseDao; class StoreProductDao extends BaseDao { protected string $alias = 'product'; // Table alias protected string $filterateField = []; // Fields to filter from search protected function setModel(): string { return StoreProduct::class; } // Custom search conditions public function search(array $where = []) { return parent::search($where); } } ``` --- ## 7. Model Guidelines ### BaseModel Pattern ```php namespace app\model\product; use crmeb\basic\BaseModel; use crmeb\traits\ModelTrait; class StoreProduct extends BaseModel { use ModelTrait; // Define searchers for field-based queries protected string $name = 'store_product'; protected string $pk = 'id'; } ``` --- ## 8. Validation Guidelines ### Validate Class Pattern ```php namespace app\validate\admin\product; use think\Validate; class StoreProductValidate extends Validate { protected $rule = [ 'name' => 'require|max:200', 'price' => 'require|float|egt:0', ]; protected $message = [ 'name.require' => '请填写商品名称', 'price.require' => '请填写价格', ]; } ``` ### Validation in Controller ```php use app\validate\admin\product\StoreProductValidate; public function save(StoreProductValidate $validate) { // Validates automatically, throws ValidateException on failure } ``` --- ## 9. Error Handling ### Custom Exceptions ```php // In crmeb/exceptions/ throw new AuthException('无权限访问', 400); throw new ApiException('参数错误', 400); throw new AdminException('操作失败', 400); ``` ### ExceptionHandle The app extends ThinkPHP's exception handling to return JSON responses: ```php // Returns: {"status": 400, "msg": "错误信息", "data": {...}} ``` --- ## 10. Middleware Guidelines ### Middleware Interface Pattern ```php namespace app\http\middleware; use app\http\middleware\BaseMiddleware; use app\interfaces\MiddlewareInterface; class AuthMiddleware implements MiddlewareInterface { public function handle(Request $request, \Closure $next) { // Before logic $response = $next($request); // After logic return $response; } } ``` --- ## 11. Important Patterns ### Transactions ```php // In services $this->transaction(function () use ($data) { $this->save($data); $this->dao->incUpdate($id, 'views', 1); }); ``` ### JSON Response Helper ```php // Available in controllers via BaseController return $this->success($data); return $this->fail('Error message'); return app('json')->code(500)->make(400, 'msg', $data); ``` ### Magic Methods in Request ```php // These are available via __call in Request class $uid = $this->request->uid(); $adminInfo = $this->request->adminInfo(); $tokenData = $this->request->tokenData(); ``` --- ## 12. Type Hints - Use strict type hints: `public function get(int $id): ?array` - Return types required for public methods - Nullable types using `?` prefix