Search code examples
cakephpcomponentsmodels

Data logic on load using a component - cakePHP


I have a project I'm developing which includes articles that can be commented on (comments stored in separate table of course). I want to perform pre logic on a field from each comment, wherever they are loaded through-out the app. The data logic I want to performed is from a custom written component.

The logical place to me that this could be achieved globally is from the comment model, but I could be wrong. I'm not even 100% if I can use a component from a model, but I've been trying to do this logic using the afterFind() call-back function:

    function afterFind($results) {
        foreach ($results as $key => $val) {
            if (isset($val['Comment']['created'])) {
                $results[$key]['Comment']['created'] = $this->Dateconvert->howLongAgo($val['Comment']['created']);;
            }
        }
        return $results;
    }

I have tried echoing from inside this function and it doesn't actually seem to be getting called but searching hasn't revealed any functions that do, but I believe afterFind() is best to illustrate what I'm trying to achieve.

So I am looking for a solution where I can performed the post-load logic on articles comments, whether they are being loaded from other controllers with associations to comments or in the comments controller. Basically a global one hit solution :D


Solution

  • cakephp indicates that components are for controllers and behaviours for models and helpers for view...

    knowing that first, you may also know that you can use any part of it wherever you want because cake still php, though is not recomended... if is a library of functions you may want to put it inside the libs folders and access it from there.

    how, easy use App::import('component', 'nameComponent'); component can be lib, controller, etc..

    Having said that, afterFind is a good place to do after load things, remember that this function is call ONLY when a find is used, if you use, any other like query or save or update it won't be called.

    hope this helps you :)