CodeIgniter Forums
Design Pattern question: how to "merge" Entities and Models? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=31)
+--- Thread: Design Pattern question: how to "merge" Entities and Models? (/showthread.php?tid=82639)



Design Pattern question: how to "merge" Entities and Models? - tgix - 08-03-2022

Hi,
I have a case where I'd like to mimic the JavaScript front-end design but can't see the best to do that in CI4 using the Models and Entities.
The system has an Admin with multiple settings (+50) for various parts of the system. I want to allow an Admin to be member of one or more AdminGroup where these 50+ settings can be stored and managed. In JS I have created a AdminGroupModel containing the settings and then an AdminModel extending AdminGroupModel and adding additional fields such as firstname, lastname and email. 
My rationale for this approach is that I only have to manage the settings in one place, for example when adding new features.
So for this to work, in AdminModel I need to merge the protected properties defined in AdminGroupModel with the fields required for the AdminModel. Same for the Entities defined.
I have been thinking like this:

(UPDATE: corrected some mistakes with the scope that I found so far)

PHP Code:
class AdminGroupModel extends BaseModel
{
    protected $commonFields = [
        // Defining all common settings here, such as:
        'access_users''access_companies',
        'item_version'
    ];

    public function 
__construct(?ConnectionInterface &$db null, ?ValidationInterface $validation null)
    {
        
$fields get_class_vars(self::class)['commonFields'];
        
$this->allowedFields += $fields;

        
parent::__construct($db$validation);
    }


And then in AdminModel:
PHP Code:
<?php
class AdminModel extends AdminGroupModel
{

    protected $allowedFields = [
        'firstname''lastname''email'
    ];



Would this be a viable approach? Any hints greatly appreciated.
/Mattias


RE: Design Pattern question: how to "merge" Entities and Models? - ozornick - 08-03-2022

AdminModel contains fields from commonFields in the table?
I didn’t quite understand the question, maybe it’s worth looking towards afterFind () to set values.
Your version looks to be working.


RE: Design Pattern question: how to "merge" Entities and Models? - tgix - 08-04-2022

(08-03-2022, 11:17 PM)ozornick Wrote: AdminModel contains fields from commonFields in the table?
I didn’t quite understand the question, maybe it’s worth looking towards afterFind () to set values.
Your version looks to be working.

Yes, the tables for Admin and AdminGroup contains the same fields for historical reasons. Now with additional requirements we would like to make it possible to "OR" the fields from Admin with zero or more AdminGroup(s).