Housni
Housni

Reputation: 983

Li3: Find filter in parent class not triggering when child calls find()

This is a question on Li3 philosophy. I have a child class, trying to run find() on a parent class which as a filter on its find() but that doesn't get executed when the child calls find().

I have a Members model extending a Users mode. The Users model has some filters:

<?php
# Users.php
namespace app\models;

class Users extends \lithium\data\Model {
}

Users::applyFilter('find', function($self, $params, $chain) {
    echo __LINE__;
    return $chain->next($self, $params, $chain);
});

Users::applyFilter('save', function($self, $params, $chain) {
    echo __LINE__;
    return $chain->next($self, $params, $chain);
});
?>

<?php
# Members.php
namespace app\models;

class Members extends \app\models\Users {
}
?>

If I use the Members model in any controller and attempt to execute a find() or a save() on Members, the filters won't be triggered.

<?php
# FooController.php
namespace app\controllers;

use app\models\Members;

class FooController extends \lithium\action\Controller {
    public function bar() {
        $bar = Members::find();
        return compact('bar');
    }

    public function baz() {
        $baz = Members::create();
        $baz->save([
            'type' => 'addiction',
            'framework' => 'lithium'
        ]);
        return compact('baz');
    }
}
?>

I can always omit the filters in Users and inherit + override the find() and save() methods in the Users model which would cause a call on Members::find() to trigger Users::find(), for example, but what is the Li3 philosophy on doing things this way?

Upvotes: 1

Views: 107

Answers (1)

blubear
blubear

Reputation: 441

My view is that if the code in the filters are actually part of your User model, as in doing something that is related to User's business rule, then you should override the find() and save().

And when you write a unit test for the User class, you can easily write test for those functions without having to rely on the filters on those functions not being cleared (which can be common during unit testing)

Filters should be reserved for cross cutting functionalities, such logging.

Upvotes: 1

Related Questions