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), building custom field types, creating complex queries with SelectBuilder, implementing custom API actions, or packaging extensions.
The Iron Law
BUSINESS LOGIC IN SERVICES, NOT HOOKS | DATA ACCESS VIA ENTITYMANAGER, NEVER DIRECT PDO | NEVER PASS CONTAINER AS DEPENDENCY
Accessing Container directly or writing business logic in hooks violates 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
Core Concepts
- 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
Advanced Topics
- SelectBuilder: Advanced querying with SelectBuilder - complex queries, joins, aggregations, and query optimization
- API Actions: Creating custom API endpoints - action handlers, request/response patterns, and authentication
- Custom Field Types: Building custom field types - backend, frontend, metadata, and integration
UI and Integration
- Frontend Customization: View system, client-side development, and UI customization
- Common Tasks: Scheduled jobs, emails, PDFs, ACL, workflows, and integration patterns
- Extension Packages: Packaging and distributing extensions - manifest files, installation, and versioning
Quality Assurance
- Testing and Debugging: Unit tests, debugging techniques, performance optimization, and common pitfalls
- PHP Quality Anti-Patterns: Language-level robustness/changeability defects — PHP4 constructor naming, uppercased control keywords,
goto, and empty catch blocks, with compliant examples (derived from CAST Highlight code quality indicators, https://doc.casthighlight.com/)
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: espocrm3description: Comprehensive guide for developing on EspoCRM - metadata-driven CRM with service layer architecture4license: MIT5---67# EspoCRM Development89## Overview1011EspoCRM 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.1213## When to Use This Skill1415Activate 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), building custom field types, creating complex queries with SelectBuilder, implementing custom API actions, or packaging extensions.1617## The Iron Law1819**BUSINESS LOGIC IN SERVICES, NOT HOOKS | DATA ACCESS VIA ENTITYMANAGER, NEVER DIRECT PDO | NEVER PASS CONTAINER AS DEPENDENCY**2021Accessing Container directly or writing business logic in hooks violates architecture.2223## Core Architecture Principles24251. **Metadata-Driven**: Entity definitions, layouts, field configs live in JSON262. **Service Layer**: All business logic implemented in Service classes273. **ORM EntityManager**: Central access point for all database operations284. **Dependency Injection**: Constructor injection, never pass Container295. **Hook System**: Lifecycle events for validation and side effects (not business logic)306. **Repository Pattern**: Entities accessed through repositories3132## Quick Start33341. **Setup Development Environment** - Use ext-template, work in `src/` directory (EspoCRM 7.4+), understand metadata structure: `custom/Espo/Modules/{ModuleName}/Resources/metadata/`35362. **Access Data with EntityManager**37 ```php38 use Espo\ORM\EntityManager;3940 public function __construct(private EntityManager $entityManager) {}4142 // Find entity43 $account = $this->entityManager->getEntityById('Account', $id);4445 // Query with conditions46 $collection = $this->entityManager47 ->getRDBRepository('Contact')48 ->where(['accountId' => $accountId])49 ->find();50 ```51523. **Implement Business Logic in Services**53 ```php54 namespace Espo\Modules\MyModule\Services;5556 use Espo\Services\Record;5758 class MyEntity extends Record {59 public function customAction(string $id, object $data): object {60 // Business logic here61 $entity = $this->entityManager->getEntityById($this->entityType, $id);62 // ... process ...63 $this->entityManager->saveEntity($entity);64 return $entity;65 }66 }67 ```68694. **Register Hooks for Lifecycle Events**70 ```php71 namespace Espo\Modules\MyModule\Hooks\Account;7273 use Espo\ORM\Entity;74 use Espo\Core\Hook\Hook\BeforeSave;7576 class MyHook implements BeforeSave {77 public function beforeSave(Entity $entity, array $options): void {78 // Validation or side effects only79 if ($entity->isAttributeChanged('status')) {80 // React to changes81 }82 }83 }84 ```85865. **Rebuild Cache After Changes**87 ```bash88 bin/command rebuild89 ```9091## Hook Types (Interfaces)9293EspoCRM 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).9495## Navigation9697### Core Concepts98- **[Architecture](references/architecture.md)**: Metadata system, ORM, DI container, repository pattern, and core architectural patterns99- **[Development Workflow](references/development-workflow.md)**: Module creation, custom entities, fields, APIs, and extension development process100- **[Hooks and Services](references/hooks-and-services.md)**: Service layer implementation, hook types, dependency injection, and business logic patterns101102### Advanced Topics103- **[SelectBuilder](references/select-builder.md)**: Advanced querying with SelectBuilder - complex queries, joins, aggregations, and query optimization104- **[API Actions](references/api-actions.md)**: Creating custom API endpoints - action handlers, request/response patterns, and authentication105- **[Custom Field Types](references/custom-field-types.md)**: Building custom field types - backend, frontend, metadata, and integration106107### UI and Integration108- **[Frontend Customization](references/frontend-customization.md)**: View system, client-side development, and UI customization109- **[Common Tasks](references/common-tasks.md)**: Scheduled jobs, emails, PDFs, ACL, workflows, and integration patterns110- **[Extension Packages](references/extension-packages.md)**: Packaging and distributing extensions - manifest files, installation, and versioning111112### Quality Assurance113- **[Testing and Debugging](references/testing-debugging.md)**: Unit tests, debugging techniques, performance optimization, and common pitfalls114- **[PHP Quality Anti-Patterns](references/php-quality-antipatterns.md)**: Language-level robustness/changeability defects — PHP4 constructor naming, uppercased control keywords, `goto`, and empty `catch` blocks, with compliant examples (derived from CAST Highlight code quality indicators, https://doc.casthighlight.com/)115116## Key Patterns117118**Correct Pattern:**119```php120✅ Service with injected dependencies121✅ EntityManager for data access122✅ Hooks using interfaces123✅ Type declarations on all methods124✅ Exceptions for error handling125```126127**Incorrect Patterns:**128```php129❌ Passing Container as dependency130❌ Direct PDO database access131❌ Business logic in hooks132❌ Hook base classes instead of interfaces133❌ Missing type declarations134```135136## Common Mistakes to Avoid137138- **Never pass Container** - Inject specific dependencies instead139- **Don't bypass EntityManager** - Use ORM, not raw queries140- **Business logic doesn't belong in hooks** - Use Services141- **Always rebuild cache** - After metadata changes (`bin/command rebuild`)142- **Use interfaces for hooks** - Not base classes143- **Type everything** - PHP 7.4+ requires type declarations144- **Throw exceptions** - Don't return booleans for errors145146## Integration with Other Skills147148- **systematic-debugging**: Debug EspoCRM issues using logs and step debugging149- **verification-before-completion**: Always test with cache rebuild before claiming complete150- **test-driven-development**: Write unit tests for Services and hooks151152## The Bottom Line153154**EspoCRM is metadata-driven with a service layer architecture.**155156Understand the metadata system. Use EntityManager for data. Implement business logic in Services. Use hooks for lifecycle events only. Rebuild cache after changes.157158This is the EspoCRM way.