analyze-yii2-project
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAnalyze Yii2 Project Workflow
Yii2项目分析工作流
Purpose
目的
Comprehensive workflow for analyzing legacy Yii2 projects to extract business logic, understand architecture, and plan modernization.
用于分析遗留Yii2项目的全面工作流,可提取业务逻辑、理解架构并规划现代化改造。
When to Use
适用场景
- ✅ User provides Yii2 codebase for analysis
- ✅ Planning Yii2 → NestJS/Modern framework migration
- ✅ Need to understand undocumented Yii2 project
- ✅ Extracting business requirements from Yii2 code
- ✅ Technical debt assessment of Yii2 application
- ✅ 用户提供Yii2代码库用于分析
- ✅ 规划Yii2 → NestJS/现代框架迁移
- ✅ 需要理解无文档的Yii2项目
- ✅ 从Yii2代码中提取业务需求
- ✅ 评估Yii2应用的技术债务
Prerequisites
前置条件
Infrastructure Check
基础设施检查
bash
codecompass healthVerify:
- ✅ Weaviate running (localhost:8081)
- ✅ Ollama running (localhost:11434)
- ✅ PostgreSQL running (localhost:5433)
bash
codecompass health验证项:
- ✅ Weaviate已运行(localhost:8081)
- ✅ Ollama已运行(localhost:11434)
- ✅ PostgreSQL已运行(localhost:5433)
Project Requirements
项目要求
- Yii2 project directory accessible
- directory present (run
vendor/if missing)composer install - Read permissions on all files
- 可访问Yii2项目目录
- 存在目录(若缺失请运行
vendor/)composer install - 所有文件具备读取权限
Step-by-Step Workflow
分步工作流
Phase 1: Initial Scan (Quick Overview)
阶段1:初始扫描(快速概览)
Step 1.1: Run Yii2 Analyzer
bash
codecompass analyze:yii2 <path-to-yii2-project>What this does:
- Scans directory structure
- Detects Yii2 version
- Identifies conventions (controllers, models, views)
- Extracts routing patterns
- Maps database migrations
Expected output:
- Framework version
- Directory structure validation
- Controller/Model counts
- Migration history
Step 1.2: Validate Results
Check for:
- ❌ Missing → Run
vendor/composer install - ❌ Old Yii2 version (<2.0.40) → Check compatibility notes in
docs/YII2_QUICK_REFERENCE.md - ❌ Non-standard structure → May need manual configuration
步骤1.1:运行Yii2分析器
bash
codecompass analyze:yii2 <path-to-yii2-project>此步骤的作用:
- 扫描目录结构
- 检测Yii2版本
- 识别约定规范(控制器、模型、视图)
- 提取路由模式
- 映射数据库迁移记录
预期输出:
- 框架版本
- 目录结构验证结果
- 控制器/模型数量
- 迁移历史记录
步骤1.2:验证结果
检查以下问题:
- ❌ 缺失目录 → 运行
vendor/composer install - ❌ Yii2版本过旧(<2.0.40) → 查看中的兼容性说明
docs/YII2_QUICK_REFERENCE.md - ❌ 非标准目录结构 → 可能需要手动配置
Phase 2: Business Capability Extraction
阶段2:业务能力提取
Step 2.1: Extract Controllers → Capabilities
bash
undefined步骤2.1:从控制器提取业务能力
bash
undefinedAnalyzer automatically extracts business capabilities from controllers
分析器会自动从控制器中提取业务能力
**What this maps**:Controller → Business Capability
├── UserController → User Management
├── OrderController → Order Processing
├── PaymentController → Payment Handling
└── ReportController → Reporting & Analytics
**Step 2.2: Extract Models → Domain Entities**
**Identifies**:
- ActiveRecord models → Database entities
- Validation rules → Business rules
- Relationships → Domain model connections
**Step 2.3: Extract Migrations → Data Model Evolution**
**Traces**:
- Schema changes over time
- Business logic embedded in migrations
- Data transformation patterns
**映射关系**:控制器 → 业务能力
├── UserController → 用户管理
├── OrderController → 订单处理
├── PaymentController → 支付处理
└── ReportController → 报表与分析
**步骤2.2:从模型提取领域实体**
**识别内容**:
- ActiveRecord模型 → 数据库实体
- 验证规则 → 业务规则
- 关联关系 → 领域模型连接
**步骤2.3:从迁移记录提取数据模型演进**
**追踪内容**:
- 随时间变化的架构变更
- 嵌入迁移记录中的业务逻辑
- 数据转换模式Phase 3: Dependency Analysis
阶段3:依赖分析
Step 3.1: Analyze Class Dependencies
Uses: for PHP parsing
AstAnalyzerServiceMaps:
- Tight coupling (classes depending on many others)
- Circular dependencies (refactoring red flags)
- Inheritance hierarchies
- Service dependencies
Step 3.2: Identify Core vs Supporting Logic
Categorizes:
- Core Domain: Business-critical logic (preserve carefully)
- Supporting: Infrastructure, utilities (can be replaced)
- Generic: Framework boilerplate (discard in migration)
步骤3.1:分析类依赖
使用工具:进行PHP解析
AstAnalyzerService映射内容:
- 紧耦合(依赖多个其他类的类)
- 循环依赖(重构预警信号)
- 继承层级
- 服务依赖
步骤3.2:区分核心逻辑与支撑逻辑
分类:
- 核心领域: 业务关键逻辑(需谨慎保留)
- 支撑逻辑: 基础设施、工具类(可替换)
- 通用逻辑: 框架模板代码(迁移时可丢弃)
Phase 4: Requirements Extraction
阶段4:需求提取
Step 4.1: Run Requirements Extractor
bash
codecompass requirements:extract --project-id <yii2-project-id>Extracts:
- Validation rules from models → Business constraints
- Controller actions → Use cases
- RBAC rules (if present) → Authorization requirements
- Database constraints → Data integrity rules
Step 4.2: Generate Documentation
Outputs:
- Business capability map (Markdown)
- Domain model diagram (Mermaid)
- Use case catalog
- Data dictionary
步骤4.1:运行需求提取器
bash
codecompass requirements:extract --project-id <yii2-project-id>提取内容:
- 模型中的验证规则 → 业务约束
- 控制器操作 → 用例
- RBAC规则(若存在) → 授权需求
- 数据库约束 → 数据完整性规则
步骤4.2:生成文档
输出内容:
- 业务能力图谱(Markdown格式)
- 领域模型图(Mermaid格式)
- 用例目录
- 数据字典
Phase 5: Semantic Indexing (Optional but Recommended)
阶段5:语义索引(可选但推荐)
Step 5.1: Index Codebase
bash
codecompass batch:index <path-to-yii2-project>Why:
- Enables semantic search for "business logic for payment processing"
- Cross-file pattern discovery
- Similar code detection
- Natural language queries
Step 5.2: Verify Indexing
bash
curl http://localhost:8081/v1/schema步骤5.1:索引代码库
bash
codecompass batch:index <path-to-yii2-project>作用:
- 支持语义搜索,例如搜索“支付处理的业务逻辑”
- 跨文件模式发现
- 相似代码检测
- 自然语言查询
步骤5.2:验证索引
bash
curl http://localhost:8081/v1/schemaCheck for CodeContext or AtlasCode collection
检查是否存在CodeContext或AtlasCode集合
**Step 5.3: Test Semantic Search**
```bash
codecompass search:semantic "validation rules for customer registration"Should return: User model validators, controller logic, related code
**步骤5.3:测试语义搜索**
```bash
codecompass search:semantic "validation rules for customer registration"应返回内容:用户模型验证器、控制器逻辑、相关代码
Phase 6: Migration Planning
阶段6:迁移规划
Step 6.1: Identify Migration Complexity
Assess:
- Low complexity: CRUD operations, standard patterns
- Medium complexity: Custom workflows, business rules
- High complexity: Legacy integrations, undocumented logic
Step 6.2: Prioritize by Business Value
Map:
Business Capability → Migration Priority
├── Core Revenue Generating → HIGH (do first, carefully)
├── Customer-Facing → MEDIUM (visible impact)
└── Internal Tools → LOW (can defer)Step 6.3: Generate Migration Roadmap
Structure:
- Infrastructure setup (NestJS, TypeORM, etc.)
- Domain models (migrate ActiveRecords → TypeORM entities)
- Core business logic (preserve carefully)
- API layer (REST/GraphQL endpoints)
- Background jobs (if using Yii2 queue)
- Testing & validation
步骤6.1:识别迁移复杂度
评估维度:
- 低复杂度: CRUD操作、标准模式
- 中复杂度: 自定义工作流、业务规则
- 高复杂度: 遗留系统集成、无文档逻辑
步骤6.2:按业务价值优先级排序
映射关系:
业务能力 → 迁移优先级
├── 核心营收相关 → HIGH(优先处理,需谨慎)
├── 面向客户 → MEDIUM(可见影响)
└── 内部工具 → LOW(可延后)步骤6.3:生成迁移路线图
结构:
- 基础设施搭建(NestJS、TypeORM等)
- 领域模型(将ActiveRecords迁移为TypeORM实体)
- 核心业务逻辑(谨慎保留)
- API层(REST/GraphQL端点)
- 后台任务(若使用Yii2队列)
- 测试与验证
Common Patterns to Look For
需要关注的常见模式
Yii2 Controller Patterns
Yii2控制器模式
php
// CRUD pattern
public function actionIndex() // → LIST endpoint
public function actionView($id) // → GET/:id endpoint
public function actionCreate() // → POST endpoint
public function actionUpdate($id) // → PUT/:id endpoint
public function actionDelete($id) // → DELETE/:id endpointMaps to NestJS:
typescript
@Controller('users')
export class UsersController {
@Get() findAll()
@Get(':id') findOne()
@Post() create()
@Put(':id') update()
@Delete(':id') remove()
}php
// CRUD模式
public function actionIndex() // → LIST端点
public function actionView($id) // → GET/:id端点
public function actionCreate() // → POST端点
public function actionUpdate($id) // → PUT/:id端点
public function actionDelete($id) // → DELETE/:id端点对应NestJS实现:
typescript
@Controller('users')
export class UsersController {
@Get() findAll()
@Get(':id') findOne()
@Post() create()
@Put(':id') update()
@Delete(':id') remove()
}Yii2 Model Patterns
Yii2模型模式
php
// Validation rules
public function rules() {
return [
[['email'], 'required'],
[['email'], 'email'],
];
}Maps to NestJS DTO:
typescript
export class CreateUserDto {
@IsNotEmpty()
@IsEmail()
email: string;
}php
// 验证规则
public function rules() {
return [
[['email'], 'required'],
[['email'], 'email'],
];
}对应NestJS DTO:
typescript
export class CreateUserDto {
@IsNotEmpty()
@IsEmail()
email: string;
}Yii2 Database Patterns
Yii2数据库模式
php
// ActiveRecord query
$users = User::find()
->where(['status' => User::STATUS_ACTIVE])
->orderBy('created_at DESC')
->all();Maps to TypeORM:
typescript
const users = await this.userRepository.find({
where: { status: UserStatus.ACTIVE },
order: { createdAt: 'DESC' },
});php
// ActiveRecord查询
$users = User::find()
->where(['status' => User::STATUS_ACTIVE])
->orderBy('created_at DESC')
->all();对应TypeORM实现:
typescript
const users = await this.userRepository.find({
where: { status: UserStatus.ACTIVE },
order: { createdAt: 'DESC' },
});Output Artifacts
输出产物
1. Architecture Diagram (Mermaid)
1. 架构图(Mermaid格式)
mermaid
graph TD
Controller[Controllers] --> Service[Business Logic]
Service --> Model[ActiveRecord Models]
Model --> DB[(Database)]
Controller --> View[Views]mermaid
graph TD
Controller[Controllers] --> Service[Business Logic]
Service --> Model[ActiveRecord Models]
Model --> DB[(Database)]
Controller --> View[Views]2. Business Capability Map
2. 业务能力图谱
markdown
undefinedmarkdown
undefinedCore Capabilities
核心能力
- User Management (UserController, User model)
- Order Processing (OrderController, Order/OrderItem models)
- Payment Handling (PaymentController, Payment model)
- 用户管理(UserController、User模型)
- 订单处理(OrderController、Order/OrderItem模型)
- 支付处理(PaymentController、Payment模型)
Supporting Capabilities
支撑能力
- Reporting (ReportController)
- Notifications (EmailService)
undefined- 报表(ReportController)
- 通知(EmailService)
undefined3. Migration Checklist
3. 迁移 checklist
- Set up NestJS project structure
- Migrate database schema (Yii2 migrations → TypeORM migrations)
- Port models (ActiveRecord → TypeORM entities)
- Reimplement business logic (preserve rules!)
- Create API endpoints (REST/GraphQL)
- Port authentication/authorization
- Migrate background jobs
- Integration testing
- Performance testing
- Gradual rollout
- 搭建NestJS项目结构
- 迁移数据库架构(Yii2迁移记录 → TypeORM迁移记录)
- 移植模型(ActiveRecord → TypeORM实体)
- 重实现业务逻辑(务必保留规则!)
- 创建API端点(REST/GraphQL)
- 移植认证/授权机制
- 迁移后台任务
- 集成测试
- 性能测试
- 逐步上线
Common Issues & Solutions
常见问题与解决方案
Issue 1: Cannot find controllers
问题1:无法找到控制器
Symptom: Analyzer reports 0 controllers
Cause: Non-standard directory structure
Solution: Check alias configuration in Yii2, adjust paths
@app症状: 分析器报告控制器数量为0
原因: 非标准目录结构
解决方案: 检查Yii2中的别名配置,调整路径
@appIssue 2: Missing database schema
问题2:缺失数据库架构
Symptom: Cannot extract models properly
Cause: Database not accessible or migrations not run
Solution: Ensure database connection configured, run pending migrations
症状: 无法正确提取模型
原因: 数据库不可访问或未运行迁移
解决方案: 确保数据库连接已配置,运行待处理的迁移
Issue 3: Circular dependencies detected
问题3:检测到循环依赖
Symptom: Dependency graph shows circular references
Meaning: Code smell - tight coupling between modules
Action: Plan refactoring to break cycles during migration
症状: 依赖图显示循环引用
含义: 代码异味 - 模块间紧耦合
处理方式: 规划在迁移期间重构以打破循环
Issue 4: Undocumented business rules
问题4:无文档的业务规则
Symptom: Complex logic in controllers with no comments
Action:
- Use semantic search to find similar patterns
- Interview original developers if available
- Write tests to capture behavior before migration
- Document assumptions in requirements docs
症状: 控制器中存在无注释的复杂逻辑
处理方式:
- 使用语义搜索查找相似模式
- 若原开发人员可用,进行访谈
- 在迁移前编写测试以捕获现有行为
- 在需求文档中记录假设
Best Practices
最佳实践
✅ Do
✅ 建议
- Run full analysis before planning migration
- Extract ALL business rules (even implicit ones)
- Document assumptions and unknowns
- Test semantic search to validate indexing
- Create comprehensive capability map
- Prioritize by business value, not technical ease
- 在规划迁移前完成完整分析
- 提取所有业务规则(包括隐式规则)
- 记录假设与未知项
- 测试语义搜索以验证索引效果
- 创建全面的能力图谱
- 按业务价值而非技术难度排序优先级
❌ Don't
❌ 不建议
- Skip dependency analysis (will bite you later)
- Assume standard Yii2 patterns everywhere
- Ignore validation rules (they're business requirements!)
- Start coding before understanding full architecture
- Migrate everything at once (strangler fig pattern instead)
- 跳过依赖分析(后续会引发问题)
- 假设所有地方都遵循标准Yii2模式
- 忽略验证规则(它们是业务需求!)
- 在理解完整架构前就开始编码
- 一次性迁移所有内容(建议采用绞杀者模式)
Related Skills
相关技能
- - For detailed requirements extraction
extract-requirements.md - - For code exploration
semantic-search.md - - For architecture perspective
software-architect.md
- - 用于详细的需求提取
extract-requirements.md - - 用于代码探索
semantic-search.md - - 用于架构视角分析
software-architect.md
Related Modules
相关模块
From :
.ai/capabilities.json- - Main analysis module
yii2-analyzer - - PHP parsing
ast-analyzer - - Schema extraction
database-analyzer - - Business rules extraction
requirements - - Capability mapping
business-analyzer
Remember: The goal is not just to understand the code, but to preserve the business knowledge embedded in it.
来自:
.ai/capabilities.json- - 核心分析模块
yii2-analyzer - - PHP解析
ast-analyzer - - 架构提取
database-analyzer - - 业务规则提取
requirements - - 能力映射
business-analyzer
注意: 目标不仅是理解代码,还要保留嵌入其中的业务知识。