Understanding Entity and Model Classes in Concrete CMS
February 10, 2025 | by biplob.ice
Entity vs. Model in PHP
- Entity Class
- Represents a database table in an Object-Relational Mapping (ORM) system (like Doctrine).
- It is responsible for database persistence.
- It contains properties that map directly to database columns.
- Used with ORM frameworks like Doctrine or Eloquent.
- Model Class
- Does not necessarily map to a database.
- Can represent data from API responses, services, or any business logic.
- Can be used to structure and handle data without persisting it to a database.
Example of an Entity Class (Doctrine ORM in Concrete CMS)
This class represents a User
entity that maps to the database.
<?php
namespace MyApp\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="users")
*/
class User
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private int $id;
/**
* @ORM\Column(type="string", length=255)
*/
private string $name;
/**
* @ORM\Column(type="string", unique=true)
*/
private string $email;
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getEmail(): string
{
return $this->email;
}
public function setEmail(string $email): void
{
$this->email = $email;
}
}
- The
@ORM\Entity
annotation makes this class an Entity. @ORM\Table(name="Users")
specifies the table name in the database.- This class is meant to be persisted in the database.
Example of a Model Class (API Response)
This class represents a UserProfile
model created from an API response.
<?php
namespace MyApp\Model;
class UserProfile
{
private string $name;
private string $email;
private string $profilePicture;
public function __construct(array $data)
{
$this->name = $data['name'] ?? '';
$this->email = $data['email'] ?? '';
$this->profilePicture = $data['profile_picture'] ?? '';
}
public function getName(): string
{
return $this->name;
}
public function getEmail(): string
{
return $this->email;
}
public function getProfilePicture(): string
{
return $this->profilePicture;
}
public static function fromApiResponse(array $data): self
{
return new self($data);
}
}
- This does not map to a database.
- Instead, it is used to structure an API response.
- The
fromApiResponse()
method creates an object from an API response array.
Key Differences
Feature | Entity (ORM) | Model (Non-DB) |
---|---|---|
Purpose | Maps to a database table | Used for API response, business logic, or data transformation |
Persistence | Stored in a database | Not stored in a database |
Framework | Works with Doctrine ORM, Eloquent, etc. | Plain PHP or used with APIs |
Use Case | Managing users, orders, products in a database | Structuring API responses, caching, or calculations |
RELATED POSTS
View all