hello cakephp community?
i’would like to ask you a thing.
in your opinion is better to write model logics in tables or entities?
how do you decide if a method is better in a table class or in a entity class?
for example. if you have a books table associated with a reviews table and you want to create a method for retrieve the top 5 reviews of a single book, you will write it in the table or in the entity? or both?
my question is a little bit complex. I know the difference between table and entities. i work with cakephp since many years.
when i write a model function happens that the code i’m writing could be fit in table but in entity too.
how you decide if the method you are writing is better in table or entities?
If your code fits into entity after copy/paste from table there is probably something wrong with it.
Can I see example of such code, please ?
Code from your first post should be put into table, not an entity - as it will be specific to some parts of application but not all where these entities are used.
in most cases you will not use every method of an entity every time you use it.
another example could be this.
you have a Orders Table, associated with Invoices Tables.
somewhere in your app you need a method that send an email and creating the invoice.
you will write a funcion in the Orders table, passing the order id, or you will create a method in the order entity?
To provide communication between different parts of the app I would use Cake’s event system - once order is finalized correct event is triggered, and invoice is generated. (Same example was considered in event’s system related chapter of the book).
I would put code into tables as they are like factories - they produce some products - entities. So when I’m generating order, orders table can contain some logic used to create entities, for an example Table can check if customer was promised in the past a 10% off on next order and apply or not such discount, or validate voucher added in the checkout - so table would be smart , while entity will just represent static result of logic used by Table and will be dumb.
If I’m displaying list of orders in the view - I’m working with entities, not tables and I’m keen to see what was order total + what discounts were applied to the order - I do not have to know why some discounts were applied or not.