Welcome Guest, Not a member yet? Register   Sign In
Splitting responsibilities between controller and model
#1

(This post was last modified: 03-04-2024, 03:58 AM by bobw.)

I'm trying to work out the best way to handle the balance between controllers and models when migrating from CI3 to CI4.

It seems like the old system used the DataMapperExt class as the access to the underlying database. So previously I'd have:

PHP Code:
class Member extends DataMapperExt {
    ...



Then that would be instantiated by a Member_model class like:

PHP Code:
class Member_model extends CI_Model {
    ...
    protected function add($data) {
        $m = new Member();
        // validate and/or clean data
        // i.e. user might enter their name as "smith", "SMITH", etc whereas the database holds it as "Smith"
        return $m->save();
    }
    ...



Then the controller would really just forward the data on from the form:

PHP Code:
class Member extends CI_Controller {
    $mem = new Member_model();

    public function add() {
        $data $this->input->post(NULLTRUE);

        $this->mem->update($data);
    }



In CI4 it appears that the validation and tidying up is done in the controller, or at least that's how the example at https://www.codeigniter.com/user_guide/t...items.html does it but the notes on models at https://www.codeigniter.com/user_guide/m...validation suggests that you can do it within the model itself. The latter seems a bit cleaner to me.

The user model in CI4 now simply extends the core model detailing which database columns may be modified and whether there should be any validation on specific columns to make sure that someone doesn't try to enter too long a name or a negative age for example. That would mean my Member model now looks like:

PHP Code:
class Member extends Model {
    protected $table 'members';

    protected $primaryKey 'id';

    protected $useAutoIncrement true;

    protected $allowedFields = ['given_name''family_name''gender''age'];

    protected $validationRules = [
        'given_name'      => 'required|max_length[30]|alpha_numeric_space|min_length[2]',
        'family_name'    => 'required|max_length[30]|alpha_numeric_space|min_length[3]',
        'age'          => 'required|is_natural',
        ...
    ];


The controller would look similar to this...

PHP Code:
class Member extends BaseController {
    helper('form');

    public function add_member() {
        $data $this->request->getPost(['given_name''family_name''gender''age']);

        // assume that this does the titlecase manipulation amongst other things.
        $cleanData $this->tidyData($data);

        $model model('members');

        if (!$model->save($cleanData)) {
            // handle error
        }
        // display appropriate view
    }



Have I got the above right? My thoughts are to have the validation done within my models as it's then available to whichever controller ends up using it.
Reply
#2

Looks ok to me.

You can see how it is done by looking at the Shield LoginModel.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Ta. I'll have a look at that code.

I've a feeling that CI4 does a lot more out of the box than with CI3 so it's a case of learning best practice and how to use those features.
Reply
#4

A supplementary question:

Is it worth using the Entity class? A search reveals very few results for it.

In my original post I had a method to tidy the data up so if Mister Shouty typing in all caps put his name as "JOHN SMITH" which while valid isn't usual, I could convert it to "John Smith" before sending it to the model which would do the validation to check there's no unwanted characters. From the documentation https://www.codeigniter.com/user_guide/m...ities.html it seems like this is just the sort of thing an Entity class is meant for.
Reply
#5

In my opinion, the Entity is the most opinionated part of CI4.

It is designed quite differently from plain PHP objects and should be considered carefully before deciding whether to use it.
Use it only if you think the features are necessary and quite useful.

Also, if processing speed is important, you should benchmark and make your decision, as Entity will slow down processing.
In PHP, objects cost more than arrays and are much slower when using magic methods.
Therefore, using Entity may result in a significant performance loss.
Reply
#6

Ta. Entities seem as if they are syntactical sugar. I'll give them a miss for the time being.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB