"Hidden" Fields for Models - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28) +--- Forum: CodeIgniter 4 Feature Requests (https://forum.codeigniter.com/forumdisplay.php?fid=29) +--- Thread: "Hidden" Fields for Models (/showthread.php?tid=82119) |
"Hidden" Fields for Models - christianitis - 06-14-2022 Supposing I have a database model representing a user. If I set up a REST controller for the User model, I don't want the password field to be returned when it is queried. Similarly, I don't want the password to be displayed in a HTML page if I need to use it in a template. Although I'm pretty sure there's a way to do this using Entity classes (maybe by using smart getters?), I think this should be a built-in feature for Models. RE: "Hidden" Fields for Models - iRedds - 06-15-2022 In the HTML template, you yourself determine which fields to display. For an API, for example, you can use a wrapper class that will return a set of just the fields you need. PHP Code: class UserDecorator implements JsonSerializable You can specify only the required fields when working with the model. PHP Code: (new Model)->select('name', 'id')->find($id); RE: "Hidden" Fields for Models - MGatner - 06-16-2022 Very nice coverage from @iRedds. I would recommend this as a general practice regardless of sensitive fields. I rarely find my API resources to be 1:1 with their database counterparts. Sometimes Entity casts is enough to handle this but often I want more flexibility, like adding related entity names or aggregates, or removing redundant fields. RE: "Hidden" Fields for Models - b126 - 06-30-2022 (06-14-2022, 08:56 AM)christianitis Wrote: Supposing I have a database model representing a user. If I set up a REST controller for the User model, I don't want the password field to be returned when it is queried. Similarly, I don't want the password to be displayed in a HTML page if I need to use it in a template. Personally, I am using JMS Serializer which makes it really easy to select the fields you want to expose or to exclude. I do it thru simple annotations in my Doctrine entities. In the following example, all the fields will be excluded but the ones with @Serializer\Expose() PHP Code: /** RE: "Hidden" Fields for Models - kilishan - 06-30-2022 I agree with the philosophy of "create the data you want to return" instead of relying just on magic. So a custom function to get the API representation would be good. You might look into the PHP League's Fractal. It helps solve a number of issues around this, especially when you data gets more complex. |