You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently in code we have two problems. One is that we have inconsistency in data type returned by model functions. Some return StdClass and others return arrays. The other is that neither option offers type safety. CodeIgniter introduced Entities to represent a row in the database and arrays of entities to represent multiple rows.
@coderabbitai what would be the benefits and drawbacks of refactoring code to return entities as a convention? Does a change like this do anything to simplify model code as currently models in this project are doing too much? Are there other considerations we should be thinking about?
Note: This response was drafted by Claude (Anthropic), not coderabbitai.
Benefits of adopting Entities as a convention:
The primary gain is type safety. When every model method has a declared return type of EntityClass|null or EntityClass[], your IDE knows what properties are available at every call site. Typos become static analysis errors rather than runtime bugs. Refactoring a column name becomes a find-all-references operation rather than a grep across the whole codebase.
The secondary gain is exactly the consistency motivation behind this issue — callers no longer need to know whether a given model returns arrays or stdClass. The answer is always: an Entity, or an array of Entities.
A smaller but real benefit: Entities give you a natural home for property-level casting and simple derived properties. $sale->isComplete() or $item->getQuantityAtLocation(int $id) belong on an Entity, not in a model method or a controller.
Drawbacks:
The migration cost is significant. OSPOS has many models, and retrofitting Entities means touching every model plus every caller that currently destructures arrays or accesses stdClass properties. Done incompletely it creates a third inconsistency layer on top of the existing two.
CI4 Entities also have a minor friction point with AJAX endpoints — they don't json_encode() as naturally as arrays and require either a toArray() call or a custom jsonSerialize() implementation on each Entity.
Does this simplify model code?
Not directly — but it creates the right conditions for simplification. The current problem is that OSPOS models are acting as DAO + business logic + data transformation simultaneously. Entities don't fix that by themselves, but they establish the BO/DAO separation (Entity = business object, Model = data access) that makes a Service layer possible. Once you have that separation, complex orchestration logic — currently living in controllers and lib files — has somewhere clean to go.
Other considerations:
DTOs deserve a mention alongside Entities. An Entity represents a database row; a DTO represents data moving between layers, such as a validated form submission. The StockLocationCommand suggested in #4643 is an example of the latter. For models that handle complex write operations, having both an Entity (for reads/output) and a DTO (for writes/input) is the cleanest pattern, though it's more investment per table.
A pragmatic path forward: implement Entities fully for one high-value model (Sale or Item), document it as the new convention in CONTRIBUTING, and require Entities for all new model work going forward. Let the migration spread organically as existing models are touched for other reasons, rather than a big-bang refactor.
The AJAX friction concern is largely solved by implementing JsonSerializable on a shared base Entity class:
Php
class BaseEntity extends Entity implements JsonSerializable
{
public function jsonSerialize(): mixed
{
return $this->toArray();
}
}
After that, json_encode($entity) and json_encode($entityArray) work naturally at every call site with no changes to controller code. All OSPOS Entities would extend BaseEntity rather than CI4's Entity directly.
For json_decode() the conversion happens at the input layer rather than the Entity — decoded JSON becomes a DTO, which is validated and passed to the model. The Entity never needs to handle deserialization.
@jekkos I would suggest that if we adopt this convention, it be done one PR per model/entity to keep the pull requests as small as possible. We can also create the entities as a phase 1 before they are being used, then as a phase 2 do one model at a time and maybe start with a simple model as a proof of concept. What do you think?
Note: This response was drafted by Claude (Anthropic), not coderabbitai.
Currently postSave() in Items is doing roughly seven things: parsing and validating POST input, handling image upload, determining insert vs update, saving item data, saving item attributes, saving item quantities per location, saving item taxes, and saving kit components. That's one controller method doing the work of multiple layers.
With ItemEntity, ItemModel, and an ItemService, the controller method collapses to four lines of real logic: parse the request into an ItemSaveDTO, validate it, delegate entirely to ItemService::save(), and return the JSON response. No business logic, no model calls, no image handling.
public function postSave(int $itemId = NEW_ENTRY): ResponseInterface
{
// 1. Parse input into a DTO
$dto = ItemSaveDTO::fromRequest($this->request);
// 2. Validate
if (!$this->validate($dto->rules())) {
return $this->response->setJSON(['success' => false, 'errors' => $this->validator->getErrors()]);
}
// 3. Delegate entirely to the service
$success = $this->itemService->save($dto, $itemId);
// 4. Return response
return $this->response->setJSON(['success' => $success]);
}
Everything else moves out. Image handling goes into ItemSaveDTO::fromRequest() or a dedicated ImageService. Insert vs update logic goes into ItemService::save(). Attributes, quantities, taxes, and kit component persistence all become orchestration inside ItemService::save(), which calls the relevant models. Each model method returns a typed Entity rather than a raw array.
The Service becomes the seam where all multi-model coordination lives. Each Model stays focused on its own table. The Controller becomes an HTTP adapter — it knows about requests and responses, and nothing else. The result is that each concern is independently testable: you can unit test ItemService::save() without an HTTP request, and you can test the controller without touching the database.
Status: Still open / not implemented — this is a design discussion, not a specific bug, and no Entities have been adopted yet.
A repo-wide search for extends Entity (CodeIgniter 4's CodeIgniter\Entity\Entity) returns zero matches in app/ — models still return stdClass/arrays rather than typed Entities, consistent with the inconsistency this issue describes. The issue is labeled on hold with milestone 4.0.0, and the discussion thread ends with a maintainer decision to prioritize fixing outstanding issues before taking on this larger refactor. No PR or model has adopted the proposed BaseEntity/ItemEntity/Service-layer pattern yet, so the feature request remains unimplemented on master, consistent with its "on hold" status.
Activity
objecttothis commentedon Aug 27, 2026
Benefits of adopting Entities as a convention:
The primary gain is type safety. When every model method has a declared return type of
EntityClass|nullorEntityClass[], your IDE knows what properties are available at every call site. Typos become static analysis errors rather than runtime bugs. Refactoring a column name becomes a find-all-references operation rather than a grep across the whole codebase.The secondary gain is exactly the consistency motivation behind this issue — callers no longer need to know whether a given model returns arrays or stdClass. The answer is always: an Entity, or an array of Entities.
A smaller but real benefit: Entities give you a natural home for property-level casting and simple derived properties.
$sale->isComplete()or$item->getQuantityAtLocation(int $id)belong on an Entity, not in a model method or a controller.Drawbacks:
The migration cost is significant. OSPOS has many models, and retrofitting Entities means touching every model plus every caller that currently destructures arrays or accesses stdClass properties. Done incompletely it creates a third inconsistency layer on top of the existing two.
CI4 Entities also have a minor friction point with AJAX endpoints — they don't
json_encode()as naturally as arrays and require either atoArray()call or a customjsonSerialize()implementation on each Entity.Does this simplify model code?
Not directly — but it creates the right conditions for simplification. The current problem is that OSPOS models are acting as DAO + business logic + data transformation simultaneously. Entities don't fix that by themselves, but they establish the BO/DAO separation (Entity = business object, Model = data access) that makes a Service layer possible. Once you have that separation, complex orchestration logic — currently living in controllers and lib files — has somewhere clean to go.
Other considerations:
DTOs deserve a mention alongside Entities. An Entity represents a database row; a DTO represents data moving between layers, such as a validated form submission. The
StockLocationCommandsuggested in #4643 is an example of the latter. For models that handle complex write operations, having both an Entity (for reads/output) and a DTO (for writes/input) is the cleanest pattern, though it's more investment per table.A pragmatic path forward: implement Entities fully for one high-value model (
SaleorItem), document it as the new convention in CONTRIBUTING, and require Entities for all new model work going forward. Let the migration spread organically as existing models are touched for other reasons, rather than a big-bang refactor.objecttothis commentedon Aug 27, 2026
Can json_encode/json_decode be overloaded in the entities to provide a natural conversion rather than needing to convert to an array first?
objecttothis commentedon Aug 27, 2026
The AJAX friction concern is largely solved by implementing JsonSerializable on a shared base Entity class:
Php
After that, json_encode($entity) and json_encode($entityArray) work naturally at every call site with no changes to controller code. All OSPOS Entities would extend BaseEntity rather than CI4's Entity directly.
For json_decode() the conversion happens at the input layer rather than the Entity — decoded JSON becomes a DTO, which is validated and passed to the model. The Entity never needs to handle deserialization.
objecttothis commentedon Aug 27, 2026
@jekkos I would suggest that if we adopt this convention, it be done one PR per model/entity to keep the pull requests as small as possible. We can also create the entities as a phase 1 before they are being used, then as a phase 2 do one model at a time and maybe start with a simple model as a proof of concept. What do you think?
objecttothis commentedon Aug 27, 2026
I have a private plugin I wrote for the plugins feature which uses entities if you want to see a PoC I can share the code with you.
objecttothis commentedon Aug 27, 2026
So if we take Items::postSave() as an example, what does that get reduced to and what does it call if we have an ItemEntity and ItemModel
objecttothis commentedon Aug 27, 2026
Note: This response was drafted by Claude (Anthropic), not coderabbitai.
Currently
postSave()in Items is doing roughly seven things: parsing and validating POST input, handling image upload, determining insert vs update, saving item data, saving item attributes, saving item quantities per location, saving item taxes, and saving kit components. That's one controller method doing the work of multiple layers.With
ItemEntity,ItemModel, and anItemService, the controller method collapses to four lines of real logic: parse the request into anItemSaveDTO, validate it, delegate entirely toItemService::save(), and return the JSON response. No business logic, no model calls, no image handling.Everything else moves out. Image handling goes into
ItemSaveDTO::fromRequest()or a dedicatedImageService. Insert vs update logic goes intoItemService::save(). Attributes, quantities, taxes, and kit component persistence all become orchestration insideItemService::save(), which calls the relevant models. Each model method returns a typed Entity rather than a raw array.The Service becomes the seam where all multi-model coordination lives. Each Model stays focused on its own table. The Controller becomes an HTTP adapter — it knows about requests and responses, and nothing else. The result is that each concern is independently testable: you can unit test
ItemService::save()without an HTTP request, and you can test the controller without touching the database.jekkos commentedon Aug 28, 2026
Sounds like that would simplify things significantly .. but the impact is huge.
Lets try to fix any outstanding issues first
objecttothis commentedon Oct 24, 2026
Claude Issue Checker Agent (cc @objecttothis)
Investigated against current
master.Status: Still open / not implemented — this is a design discussion, not a specific bug, and no Entities have been adopted yet.
A repo-wide search for
extends Entity(CodeIgniter 4'sCodeIgniter\Entity\Entity) returns zero matches inapp/— models still returnstdClass/arrays rather than typed Entities, consistent with the inconsistency this issue describes. The issue is labeledon holdwith milestone4.0.0, and the discussion thread ends with a maintainer decision to prioritize fixing outstanding issues before taking on this larger refactor. No PR or model has adopted the proposedBaseEntity/ItemEntity/Service-layer pattern yet, so the feature request remains unimplemented onmaster, consistent with its "on hold" status.