Search code examples
phpcakephpcakephp-2.6

data manipulation of paginator array in cakephp


I have Task model which has date saved as timestamp, when i paginate i wan't to be displayed as "Today", "Tomorrow", "Next Week", etc. I made custom function niceDate_hr($date) that returns string I need. But i have problem with modifying array that paginator makes. My current code is:

    $this->loadModel('Task');
    $this->Task->create();
    $this->Paginator->settings = array(
        'conditions' => array('Task.user_id' => $user['ID']),
        'limit' => 5,
        'order' => array('Task.date' => 'desc')
    );
    $tasks = $this->Paginator->paginate('Task');
    $ctask = new TasksController;
    foreach ($tasks as $task) {
        $task['Task']['date'] = $ctask->niceDate_hr($task['Task']['date']);
    }
    $this -> set('tasks', $tasks);

P.S. Forgive me about any grammar and spelling errors.


Solution

  • You're violating the MVC pattern. Don't do that: $ctask = new TasksController; There is plenty of information with details around why this is wrong. Only the dispatcher should instantiate the controller and there should be always just one controller instance. You never instantiate controllers. Except in tests.

    Further you're doing data manipulation which should, when it is required, happen in the model layer, not in the controller. But you want to format output, which should happen in the view layer.

    The proper implementation would be to move your custom method, which is as well not following the conventions (should be named camel cased), in a helper and use it in your view.

    foreach ($tasks as $task) {
           echo $this->MyFancyHelper->niceDateHr($task['Task']['date']);
    }
    

    I don't know how you format your date but CakePHP comes with a time helper that allows formatting as well.