Can we define entity attributes statically? Because of different data source

This is what i want to do: http://pastebin.com/UM0S72Vr
CakePHP’s entity feature is too dynamic. So…it will pass inconsistent data to view template. And if we defined all attributes statically, view template just know consuming $this->getTitle() do not care whatever the data source.

Can we define entity attributes statically?

You probably can, but I have never tried. Instead of extending Entity you will need to implement EntityInterface (https://github.com/cakephp/cakephp/blob/master/src/Datasource/EntityInterface.php) The interface requires you to implement some methods that look “dynamic” but you can hardcode the implementation to only look for properties that are defined in the class.

If you are concerned about not having inconsistent data, then don’t use entities in the view directly! Instead you can have objects that can be constructed from entities instead:

$article = new StrictArticle($articleEntity)

The StrictArticle class would read the properties form the entity and call the required setters or throw an exception if the data is inconsistent.

Hi @lorenzo thank you for your response.
At which class i should implement EntityInterface ? at StrictArticle class or at ArticleEntity class ?

I assume EntityInterface implemented at StrictArticle. So… maybe looks like this ?

<?php
class StrictArticle extends Entity implements EntityInterface
{
    private $title;
    private $contributor;
    private $date;
    private $viewed;
    private $content;

    
}

But, why i should implements EntityInterface if extending Entity was aready fullfill the required methods ? And where should i put StrictArticle class ?

Thank You :slight_smile:

I offered you 2 different solutions, although you are very welcome to combine them. I said that you could either implement EntityInterface or transform a class into another, like the StaticArticle example.

The reason or implementing EntityInterface is so that you can have a different implementation of the idea of an Entity, that the framework can use, but in your case, the idea of an entity is an object with only known properties.

If you implement a different entity class using EntityInterface, I would just call the class Article and put it in src/Model/Entity/Article.php

Hi Lorenzo,
Thank you for your explanation