3
votes

i have some piece of reusable functions that i want to use in my controller to manipulate the ajax data in my controller. since the controller does not have a view (because it is AJAX). i want to know where does the below method rightfully belong in a Zend Framework

function blockUnblock($value, $id) {
    $image = ($value == 0) ? 'tick.png' : 'tock.png';
    $alt = ($value == 0) ? 'Yes' : 'No';
    $src = '<a class="toggle" href="#toggle">';
    $src .= '<img src = "/css/images/'.$image.'" alt = "'.$alt.'" data-id = "'.$id.'" data-block = "'.$value.'"/>';
    $src .= '</a>';
    return $src;
}

i need to reuse this method across various controllers and actions.

which helper method does it belong to?

2
Honestly it belongs where you want it. It would make a nice view helper, or you could put it inside a class of related functions(or it's own class) and put it in the library under your own namespace. If you want you can add it as a function to your controller (I do this a lot during development to test code, when it's right I put it where I want it). It's your code, do what feels correct to you. - RockyFord

2 Answers

4
votes

Since your function is formatting html, it belongs to a View Helper in my opinion. I assume you're using AjaxContext with a json format (this would be the reason why you don't need a viewscript for this action). However, you can call any view helper from your controller anyway using:

$imageLink = $this->view->blockUnblock($value, $id);
$this->view->imageLink = $imageLink;

And your view helper would look like this:

// .../views/helpers/BlockUnblock.php
class Zend_View_Helper_BlockUnblock extends Zend_View_Helper_Abstract
{

    public function blockUnblock($value, $id)
    {
        $image = ($value == 0) ? 'tick.png' : 'tock.png';
        $alt = ($value == 0) ? 'Yes' : 'No';
        $src = '<a class="toggle" href="#toggle">';
        $src .= '<img src = "/css/images/'.$image.'" alt = "'.$alt.'" data-id = "'.$id.'" data-block = "'.$value.'"/>';
        $src .= '</a>';
        return $src;
    }
}
2
votes

There are (at least) two approaches to this problem.

The first is to create a custom controller and extend all other controllers from it. That way all controllers / actions have access to this function.

The second is to create an action view helper. This will allow the function (or class, in this case) to be called where-ever you have access to the view object.