espocrm — скилл для Claude Code: что делает и как установить
Скилл по разработке под EspoCRM. Следит за метаданными, сервисами и хуками, чтобы агент не ломал архитектуру платформы.
MIT 202 установок ★ 80 обновлён 2026-07-18
npx skills add bobmatnyc/claude-mpm-skills --skill espocrm -a claude-codeЧто делает espocrm
Скилл обучает ИИ-агента правилам разработки под EspoCRM 7.4 и выше. Он задаёт жёсткое архитектурное разделение: конфигурация сущностей и полей хранится в JSON-метаданных, бизнес-логика пишется исключительно в классах Service, а доступ к данным идёт строго через EntityManager вместо прямых SQL-запросов к PDO.
Внутрь включены руководства по созданию кастомных сущностей, расширений и хуков на базе готовых интерфейсов (BeforeSave, AfterSave, AfterRelate). Агент учится внедрять зависимости через конструктор, строить сложные выборки в SelectBuilder и писать кастомные API-эндпоинты.
Любые правки файлов в custom/Espo/Modules/{ModuleName}/Resources/metadata/ требуют сброса кэша командой bin/command rebuild, иначе CRM не увидит изменения. Передавать контейнер зависимостей напрямую скилл запрещает.
Какие задачи решает
- спроектировать модуль или кастомную сущность для EspoCRM
- написать сервисную бизнес-логику без прямого обращения к PDO
- зарегистрировать хуки жизненного цикла сущности через интерфейсы
- составить сложный запрос к базе через SelectBuilder
- собрать пакет расширения с манифестом для дистрибуции
Примеры запросов агенту
- Создай кастомную сущность Invoice в модуле Billing для EspoCRM
- Напиши хук BeforeSave для сущности Account, проверяющий смену статуса
- Построй запрос через SelectBuilder для выборки контактов с группировкой
Как установить espocrm
1Через Skills CLI (Vercel)
npx skills add bobmatnyc/claude-mpm-skills --skill espocrm -a claude-code2Вручную: положить файлы
~/.claude/skills/espocrm/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/espocrm/
1Через Skills CLI (Vercel)
npx skills add bobmatnyc/claude-mpm-skills --skill espocrm -a codex2Вручную: положить файлы
.agents/skills/espocrm/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add bobmatnyc/claude-mpm-skills --skill espocrm -a cursor2Вручную: положить файлы
.cursor/skills/espocrm/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install bobmatnyc/claude-mpm-skills toolchains/php/frameworks/espocrm2Вручную: положить файлы
.github/skills/espocrm/SKILL.md1Через Skills CLI (Vercel)
npx skills add bobmatnyc/claude-mpm-skills --skill espocrm -a gemini-cli2Командой платформы
gemini skills install https://github.com/bobmatnyc/claude-mpm-skills --path toolchains/php/frameworks/espocrmВручную: положить файлы
.devin/skills/espocrm/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add bobmatnyc/claude-mpm-skills --skill espocrm -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы об espocrm
Как установить espocrm в Claude Code?
Выполните в терминале команду npx skills add bobmatnyc/claude-mpm-skills --skill espocrm -a claude-code. Файл инструкции сохранится в ~/.claude/skills/espocrm/SKILL.md.
Что делает скилл espocrm?
Он задаёт правила разработки под EspoCRM: требует выносить логику в сервисы, работать с базой через EntityManager и запрещает передавать контейнер зависимостей напрямую.
Почему скилл запрещает писать бизнес-логику в хуках?
Архитектура EspoCRM отводит хукам только валидацию и побочные эффекты жизненного цикла. Вся прикладная логика обязана находиться в классах сервисов.
Исходный текст
SKILL.md · MIT
---
name: espocrm
description: Comprehensive guide for developing on EspoCRM - metadata-driven CRM with service layer architecture
user-invocable: false
disable-model-invocation: true
version: 1.2.0
updated: "2026-06-15"
category: development
author: Claude MPM Team
license: MIT
progressive_disclosure:
entry_point:
summary: "Metadata-driven CRM development using service layer, ORM EntityManager, and hook-based business logic"
when_to_use: "When developing custom modules, entities, hooks, or integrations for EspoCRM"
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"
references:
- architecture.md
- development-workflow.md
- hooks-and-services.md
- frontend-customization.md
- common-tasks.md
- testing-debugging.md
- select-builder.md
- api-actions.md
- custom-field-types.md
- extension-packages.md
- php-quality-antipatterns.md
context_limit: 800
tags:
- espocrm
- php
- crm
- metadata-driven
- orm
requires_tools: []
---
# 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
1. **Metadata-Driven**: Entity definitions, layouts, field configs live in JSON
2. **Service Layer**: All business logic implemented in Service classes
3. **ORM EntityManager**: Central access point for all database operations
4. **Dependency Injection**: Constructor injection, never pass Container
5. **Hook System**: Lifecycle events for validation and side effects (not business logic)
6. **Repository Pattern**: Entities accessed through repositories
## Quick Start
1. **Setup Development Environment** - Use ext-template, work in `src/` directory (EspoCRM 7.4+), understand metadata structure: `custom/Espo/Modules/{ModuleName}/Resources/metadata/`
2. **Access Data with EntityManager**
```php
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();
```
3. **Implement Business Logic in Services**
```php
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;
}
}
```
4. **Register Hooks for Lifecycle Events**
```php
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
}
}
}
```
5. **Rebuild Cache After Changes**
```bash
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](references/architecture.md)**: Metadata system, ORM, DI container, repository pattern, and core architectural patterns
- **[Development Workflow](references/development-workflow.md)**: Module creation, custom entities, fields, APIs, and extension development process
- **[Hooks and Services](references/hooks-and-services.md)**: Service layer implementation, hook types, dependency injection, and business logic patterns
### Advanced Topics
- **[SelectBuilder](references/select-builder.md)**: Advanced querying with SelectBuilder - complex queries, joins, aggregations, and query optimization
- **[API Actions](references/api-actions.md)**: Creating custom API endpoints - action handlers, request/response patterns, and authentication
- **[Custom Field Types](references/custom-field-types.md)**: Building custom field types - backend, frontend, metadata, and integration
### UI and Integration
- **[Frontend Customization](references/frontend-customization.md)**: View system, client-side development, and UI customization
- **[Common Tasks](references/common-tasks.md)**: Scheduled jobs, emails, PDFs, ACL, workflows, and integration patterns
- **[Extension Packages](references/extension-packages.md)**: Packaging and distributing extensions - manifest files, installation, and versioning
### Quality Assurance
- **[Testing and Debugging](references/testing-debugging.md)**: Unit tests, debugging techniques, performance optimization, and common pitfalls
- **[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/)
## Key Patterns
**Correct Pattern:**
```php
✅ Service with injected dependencies
✅ EntityManager for data access
✅ Hooks using interfaces
✅ Type declarations on all methods
✅ Exceptions for error handling
```
**Incorrect Patterns:**
```php
❌ 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.
© Claude MPM Team · MIT · bobmatnyc/claude-mpm-skills