Entities & Database
Define database structures using Doctrine ORM entities and manage schema changes with migrations.
Basic Entity
<?php
namespace Plugins\MyPlugin\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: MyEntityRepository::class)]
#[ORM\Table(name: 'plg_my_visit_log')]
#[ORM\Index(columns: ['created_at'], name: 'idx_created_at')]
class VisitLog
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 255)]
private string $ipAddress;
#[ORM\Column(type: 'string', length: 500)]
private string $userAgent;
#[ORM\Column(type: 'datetime_immutable')]
private \DateTimeImmutable $createdAt;
public function __construct()
{
$this->createdAt = new \DateTimeImmutable();
}
// Getters and setters
public function getId(): ?int
{
return $this->id;
}
public function getIpAddress(): string
{
return $this->ipAddress;
}
public function setIpAddress(string $ipAddress): self
{
$this->ipAddress = $ipAddress;
return $this;
}
// ... more getters/setters
}Table Naming Convention
Always use the plg_ prefix with a short plugin identifier:
Examples:
plg_hello_visit_log(hello-world plugin)plg_paypal_transaction(paypal-payment plugin)plg_my_user_data(my-plugin)
Entity Best Practices
Use DateTimeImmutable for timestamps:
Add indexes for frequently queried columns:
Use appropriate column lengths:
Add validation constraints:
Custom Repository
Using Entities in Controllers
Migrations
Migrations manage database schema changes and initial data setup.
Creating a Migration
This generates a migration file in your plugin's Migrations/ directory.
Migration Structure
Settings Initialization Migration
Create a separate migration for plugin settings:
Migration Best Practices
Use MySQL/MariaDB syntax (PteroCA's database):
Always include down() method for rollback:
Use table prefix
plg_:
Settings context must be
plugin:{plugin-name}:
Add indexes for performance:
Handle datetime immutable with comment:
Running Migrations
Migrations run automatically when plugin is enabled:
Manual migration execution:
Related Guides
Plugin Structure - Entity directory organization
Bootstrap & Lifecycle - Don't create tables in Bootstrap
CRUD Controllers - Manage entities in admin panel
Last updated