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
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.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: espocrm-development3description: Comprehensive guide for developing on EspoCRM - metadata-driven CRM with service layer architecture Use when this capability is needed.4---56# EspoCRM Development78## Overview910EspoCRM 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.1112## When to Use This Skill1314Activate 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.1516## The Iron Law1718**BUSINESS LOGIC IN SERVICES, NOT HOOKS | DATA ACCESS VIA ENTITYMANAGER, NEVER DIRECT PDO | NEVER PASS CONTAINER AS DEPENDENCY**1920Accessing Container directly or writing business logic in hooks violates architecture.2122## Core Architecture Principles23241. **Metadata-Driven**: Entity definitions, layouts, field configs live in JSON252. **Service Layer**: All business logic implemented in Service classes263. **ORM EntityManager**: Central access point for all database operations274. **Dependency Injection**: Constructor injection, never pass Container285. **Hook System**: Lifecycle events for validation and side effects (not business logic)296. **Repository Pattern**: Entities accessed through repositories3031## Quick Start32331. **Setup Development Environment** - Use ext-template, work in `src/` directory (EspoCRM 7.4+), understand metadata structure: `custom/Espo/Modules/{ModuleName}/Resources/metadata/`34352. **Access Data with EntityManager**36 ```php37 use Espo\ORM\EntityManager;3839 public function __construct(private EntityManager $entityManager) {}4041 // Find entity42 $account = $this->entityManager->getEntityById('Account', $id);4344 // Query with conditions45 $collection = $this->entityManager46 ->getRDBRepository('Contact')47 ->where(['accountId' => $accountId])48 ->find();49 ```50513. **Implement Business Logic in Services**52 ```php53 namespace Espo\Modules\MyModule\Services;5455 use Espo\Services\Record;5657 class MyEntity extends Record {58 public function customAction(string $id, object $data): object {59 // Business logic here60 $entity = $this->entityManager->getEntityById($this->entityType, $id);61 // ... process ...62 $this->entityManager->saveEntity($entity);63 return $entity;64 }65 }66 ```67684. **Register Hooks for Lifecycle Events**69 ```php70 namespace Espo\Modules\MyModule\Hooks\Account;7172 use Espo\ORM\Entity;73 use Espo\Core\Hook\Hook\BeforeSave;7475 class MyHook implements BeforeSave {76 public function beforeSave(Entity $entity, array $options): void {77 // Validation or side effects only78 if ($entity->isAttributeChanged('status')) {79 // React to changes80 }81 }82 }83 ```84855. **Rebuild Cache After Changes**86 ```bash87 bin/command rebuild88 ```8990## Hook Types (Interfaces)9192EspoCRM 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).9394## Navigation9596### Core Concepts97- **[Architecture](references/architecture.md)**: Metadata system, ORM, DI container, repository pattern, and core architectural patterns98- **[Development Workflow](references/development-workflow.md)**: Module creation, custom entities, fields, APIs, and extension development process99- **[Hooks and Services](references/hooks-and-services.md)**: Service layer implementation, hook types, dependency injection, and business logic patterns100101### Advanced Topics102- **[SelectBuilder](references/select-builder.md)**: Advanced querying with SelectBuilder - complex queries, joins, aggregations, and query optimization103- **[API Actions](references/api-actions.md)**: Creating custom API endpoints - action handlers, request/response patterns, and authentication104- **[Custom Field Types](references/custom-field-types.md)**: Building custom field types - backend, frontend, metadata, and integration105106### UI and Integration107- **[Frontend Customization](references/frontend-customization.md)**: View system, client-side development, and UI customization108- **[Common Tasks](references/common-tasks.md)**: Scheduled jobs, emails, PDFs, ACL, workflows, and integration patterns109- **[Extension Packages](references/extension-packages.md)**: Packaging and distributing extensions - manifest files, installation, and versioning110111### Quality Assurance112- **[Testing and Debugging](references/testing-debugging.md)**: Unit tests, debugging techniques, performance optimization, and common pitfalls113114## Key Patterns115116**Correct Pattern:**117```php118✅ Service with injected dependencies119✅ EntityManager for data access120✅ Hooks using interfaces121✅ Type declarations on all methods122✅ Exceptions for error handling123```124125**Incorrect Patterns:**126```php127❌ Passing Container as dependency128❌ Direct PDO database access129❌ Business logic in hooks130❌ Hook base classes instead of interfaces131❌ Missing type declarations132```133134## Common Mistakes to Avoid135136- **Never pass Container** - Inject specific dependencies instead137- **Don't bypass EntityManager** - Use ORM, not raw queries138- **Business logic doesn't belong in hooks** - Use Services139- **Always rebuild cache** - After metadata changes (`bin/command rebuild`)140- **Use interfaces for hooks** - Not base classes141- **Type everything** - PHP 7.4+ requires type declarations142- **Throw exceptions** - Don't return booleans for errors143144## Integration with Other Skills145146- **systematic-debugging**: Debug EspoCRM issues using logs and step debugging147- **verification-before-completion**: Always test with cache rebuild before claiming complete148- **test-driven-development**: Write unit tests for Services and hooks149150## The Bottom Line151152**EspoCRM is metadata-driven with a service layer architecture.**153154Understand the metadata system. Use EntityManager for data. Implement business logic in Services. Use hooks for lifecycle events only. Rebuild cache after changes.155156This is the EspoCRM way.157158---159> Converted and distributed by [TomeVault](https://tomevault.io/claim/bobmatnyc) — claim your Tome and manage your conversions.160<!-- tomevault:4.0:skill_md:2026-04-11 -->