EspoCRM Development
Overview
EspoCRM is a metadata-driven CRM platform where configuration lives in JSON files, business logic belongs in Services, and data access happens through ORM EntityManager. This skill enforces architectural patterns to prevent common mistakes like passing Container dependencies, bypassing the service layer, or implementing business logic in hooks.
When to Use This Skill
Activate when developing custom EspoCRM modules, entities, relationships, hooks, services, API endpoints, or integrations. Use especially when: working with ORM (EntityManager required), implementing business logic (belongs in Services), creating hooks (use interfaces), modifying metadata (requires cache rebuild), or building custom field types.
The Iron Law
BUSINESS LOGIC IN SERVICES, NOT HOOKS | DATA ACCESS VIA ENTITYMANAGER, NEVER DIRECT PDO | NEVER PASS CONTAINER AS DEPENDENCY
If you're accessing Container directly or writing business logic in hooks, you're violating architecture.
Core Architecture Principles
- Metadata-Driven: Entity definitions, layouts, field configs live in JSON
- Service Layer: All business logic implemented in Service classes
- ORM EntityManager: Central access point for all database operations
- Dependency Injection: Constructor injection, never pass Container
- Hook System: Lifecycle events for validation and side effects (not business logic)
- Repository Pattern: Entities accessed through repositories
Quick Start
Setup Development Environment - Use ext-template, work in src/ directory (EspoCRM 7.4+), understand metadata structure: custom/Espo/Modules/{ModuleName}/Resources/metadata/
Access Data with EntityManager
use Espo\ORM\EntityManager;
public function __construct(private EntityManager $entityManager) {}
// Find entity
$account = $this->entityManager->getEntityById('Account', $id);
// Query with conditions
$collection = $this->entityManager
->getRDBRepository('Contact')
->where(['accountId' => $accountId])
->find();
Implement Business Logic in Services
namespace Espo\Modules\MyModule\Services;
use Espo\Services\Record;
class MyEntity extends Record {
public function customAction(string $id, object $data): object {
// Business logic here
$entity = $this->entityManager->getEntityById($this->entityType, $id);
// ... process ...
$this->entityManager->saveEntity($entity);
return $entity;
}
}
Register Hooks for Lifecycle Events
namespace Espo\Modules\MyModule\Hooks\Account;
use Espo\ORM\Entity;
use Espo\Core\Hook\Hook\BeforeSave;
class MyHook implements BeforeSave {
public function beforeSave(Entity $entity, array $options): void {
// Validation or side effects only
if ($entity->isAttributeChanged('status')) {
// React to changes
}
}
}
Rebuild Cache After Changes
bin/command rebuild
Hook Types (Interfaces)
EspoCRM provides 7 hook types - ALWAYS use interfaces: BeforeSave (validation before save), AfterSave (side effects after save), BeforeRemove (validation before delete), AfterRemove (cleanup after delete), AfterRelate (relationship creation), AfterUnrelate (relationship removal), AfterMassRelate (bulk relationship operations).
Navigation
For detailed information:
- Architecture: Metadata system, ORM, DI container, repository pattern, and core architectural patterns
- Development Workflow: Module creation, custom entities, fields, APIs, and extension development process
- Hooks and Services: Service layer implementation, hook types, dependency injection, and business logic patterns
- Frontend Customization: View system, client-side development, and UI customization
- Common Tasks: Scheduled jobs, emails, PDFs, ACL, workflows, and integration patterns
- Testing and Debugging: Unit tests, debugging techniques, performance optimization, and common pitfalls
Key Patterns
Correct Pattern:
✅ Service with injected dependencies
✅ EntityManager for data access
✅ Hooks using interfaces
✅ Type declarations on all methods
✅ Exceptions for error handling
Incorrect Patterns:
❌ Passing Container as dependency
❌ Direct PDO database access
❌ Business logic in hooks
❌ Hook base classes instead of interfaces
❌ Missing type declarations
Common Mistakes to Avoid
- Never pass Container - Inject specific dependencies instead
- Don't bypass EntityManager - Use ORM, not raw queries
- Business logic doesn't belong in hooks - Use Services
- Always rebuild cache - After metadata changes (
bin/command rebuild)
- Use interfaces for hooks - Not base classes
- Type everything - PHP 7.4+ requires type declarations
- Throw exceptions - Don't return booleans for errors
Integration with Other Skills
- systematic-debugging: Debug EspoCRM issues using logs and step debugging
- verification-before-completion: Always test with cache rebuild before claiming complete
- test-driven-development: Write unit tests for Services and hooks
The Bottom Line
EspoCRM is metadata-driven with a service layer architecture.
Understand the metadata system. Use EntityManager for data. Implement business logic in Services. Use hooks for lifecycle events only. Rebuild cache after changes.
This is the EspoCRM way.
1---2name: espocrm-development3description: Comprehensive guide for developing on EspoCRM - metadata-driven CRM with service layer architecture4version: 1.0.05category: development6author: Claude MPM Team7license: MIT8progressive_disclosure:9 entry_point:10 summary: "Metadata-driven CRM development using service layer, ORM EntityManager, and hook-based business logic"11 when_to_use: "When developing custom modules, entities, hooks, or integrations for EspoCRM"12 quick_start: "1. Understand metadata-driven architecture 2. Use EntityManager for data access 3. Implement business logic in Services 4. Register hooks for lifecycle events 5. Rebuild cache after changes"13 references:14 - architecture.md15 - development-workflow.md16 - hooks-and-services.md17 - frontend-customization.md18 - common-tasks.md19 - testing-debugging.md20context_limit: 80021tags:22 - espocrm23 - php24 - crm25 - metadata-driven26 - orm27requires_tools: []28effort: high29---3031# EspoCRM Development3233## Overview3435EspoCRM is a metadata-driven CRM platform where configuration lives in JSON files, business logic belongs in Services, and data access happens through ORM EntityManager. This skill enforces architectural patterns to prevent common mistakes like passing Container dependencies, bypassing the service layer, or implementing business logic in hooks.3637## When to Use This Skill3839Activate when developing custom EspoCRM modules, entities, relationships, hooks, services, API endpoints, or integrations. **Use especially when:** working with ORM (EntityManager required), implementing business logic (belongs in Services), creating hooks (use interfaces), modifying metadata (requires cache rebuild), or building custom field types.4041## The Iron Law4243**BUSINESS LOGIC IN SERVICES, NOT HOOKS | DATA ACCESS VIA ENTITYMANAGER, NEVER DIRECT PDO | NEVER PASS CONTAINER AS DEPENDENCY**4445If you're accessing Container directly or writing business logic in hooks, you're violating architecture.4647## Core Architecture Principles48491. **Metadata-Driven**: Entity definitions, layouts, field configs live in JSON502. **Service Layer**: All business logic implemented in Service classes513. **ORM EntityManager**: Central access point for all database operations524. **Dependency Injection**: Constructor injection, never pass Container535. **Hook System**: Lifecycle events for validation and side effects (not business logic)546. **Repository Pattern**: Entities accessed through repositories5556## Quick Start57581. **Setup Development Environment** - Use ext-template, work in `src/` directory (EspoCRM 7.4+), understand metadata structure: `custom/Espo/Modules/{ModuleName}/Resources/metadata/`59602. **Access Data with EntityManager**61 ```php62 use Espo\ORM\EntityManager;6364 public function __construct(private EntityManager $entityManager) {}6566 // Find entity67 $account = $this->entityManager->getEntityById('Account', $id);6869 // Query with conditions70 $collection = $this->entityManager71 ->getRDBRepository('Contact')72 ->where(['accountId' => $accountId])73 ->find();74 ```75763. **Implement Business Logic in Services**77 ```php78 namespace Espo\Modules\MyModule\Services;7980 use Espo\Services\Record;8182 class MyEntity extends Record {83 public function customAction(string $id, object $data): object {84 // Business logic here85 $entity = $this->entityManager->getEntityById($this->entityType, $id);86 // ... process ...87 $this->entityManager->saveEntity($entity);88 return $entity;89 }90 }91 ```92934. **Register Hooks for Lifecycle Events**94 ```php95 namespace Espo\Modules\MyModule\Hooks\Account;9697 use Espo\ORM\Entity;98 use Espo\Core\Hook\Hook\BeforeSave;99100 class MyHook implements BeforeSave {101 public function beforeSave(Entity $entity, array $options): void {102 // Validation or side effects only103 if ($entity->isAttributeChanged('status')) {104 // React to changes105 }106 }107 }108 ```1091105. **Rebuild Cache After Changes**111 ```bash112 bin/command rebuild113 ```114115## Hook Types (Interfaces)116117EspoCRM provides 7 hook types - ALWAYS use interfaces: `BeforeSave` (validation before save), `AfterSave` (side effects after save), `BeforeRemove` (validation before delete), `AfterRemove` (cleanup after delete), `AfterRelate` (relationship creation), `AfterUnrelate` (relationship removal), `AfterMassRelate` (bulk relationship operations).118119## Navigation120121For detailed information:122- **[Architecture](references/architecture.md)**: Metadata system, ORM, DI container, repository pattern, and core architectural patterns123- **[Development Workflow](references/development-workflow.md)**: Module creation, custom entities, fields, APIs, and extension development process124- **[Hooks and Services](references/hooks-and-services.md)**: Service layer implementation, hook types, dependency injection, and business logic patterns125- **[Frontend Customization](references/frontend-customization.md)**: View system, client-side development, and UI customization126- **[Common Tasks](references/common-tasks.md)**: Scheduled jobs, emails, PDFs, ACL, workflows, and integration patterns127- **[Testing and Debugging](references/testing-debugging.md)**: Unit tests, debugging techniques, performance optimization, and common pitfalls128129## Key Patterns130131**Correct Pattern:**132```php133✅ Service with injected dependencies134✅ EntityManager for data access135✅ Hooks using interfaces136✅ Type declarations on all methods137✅ Exceptions for error handling138```139140**Incorrect Patterns:**141```php142❌ Passing Container as dependency143❌ Direct PDO database access144❌ Business logic in hooks145❌ Hook base classes instead of interfaces146❌ Missing type declarations147```148149## Common Mistakes to Avoid150151- **Never pass Container** - Inject specific dependencies instead152- **Don't bypass EntityManager** - Use ORM, not raw queries153- **Business logic doesn't belong in hooks** - Use Services154- **Always rebuild cache** - After metadata changes (`bin/command rebuild`)155- **Use interfaces for hooks** - Not base classes156- **Type everything** - PHP 7.4+ requires type declarations157- **Throw exceptions** - Don't return booleans for errors158159## Integration with Other Skills160161- **systematic-debugging**: Debug EspoCRM issues using logs and step debugging162- **verification-before-completion**: Always test with cache rebuild before claiming complete163- **test-driven-development**: Write unit tests for Services and hooks164165## The Bottom Line166167**EspoCRM is metadata-driven with a service layer architecture.**168169Understand the metadata system. Use EntityManager for data. Implement business logic in Services. Use hooks for lifecycle events only. Rebuild cache after changes.170171This is the EspoCRM way.