Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User defined function which I can use in all of my controllers

I have a project and I'm using ZendFramework, also I'm a newbie in this Framework.

So my problem is,

I want to create a user defined function that I can use in all the controllers. Example: I want to create a function that will validate an input field in which I'll use trim, htmlspecialchars and mysql_real_escape_string. I want to access this function in all the controllers.

I have a solution for this which is I'll create this function in every controller that I have, which I think is not the best solution.

Thanks

like image 418
SuperNoob Avatar asked Mar 26 '12 06:03

SuperNoob


2 Answers

A base controller is a solution, but not the best to me. You should write your own Action Helper, they are meant to do it.

Action Helpers allow developers to inject runtime and/or on-demand functionality into any Action Controllers that extend Zend_Controller_Action. Action Helpers aim to minimize the necessity to extend the abstract Action Controller in order to inject common Action Controller functionality.

More information here in the manual.

Let's see how to register your Action Helper path, add this in your application.ini:

resources.frontController.actionHelperPaths.My_Controller_Action_Helper = "My/Controller/Action/Helper/"

where My is the name of you custom library.

And in the path My/Controller/Action/Helper/ you can add a file MyActionHelper.php as follow:

class My_Controller_Action_Helper_MyActionHelper extends Zend_Controller_Action_Helper_Abstract
{
    public function direct($input)
    {
        $output = mysql_real_escape_string($input);
        // trim, etc.
        return $output;
    }
}

That's all you need to do! Finally, you can access your action helper from any controller using $this->_helper->myActionHelper($input);.

If you need to validate an input coming from a form, take a look at Zend_Form and Zend_Filter. Zend_Filter can natively StripTags and TrimString, it's even a better way to do it.

like image 170
Liyali Avatar answered Oct 23 '22 07:10

Liyali


Create file Util.php put it inside library folder and add as many functions you want into it then open index.php (inside public folder)

add

require_once 'Util.php';

after line

require_once 'Zend/Application.php';

So for e.g your Util.php will migh look like

    function mysql_real_escape_string($value)
    {
    return $value 
    }

    function logger($value)
    {
      Zend_Regsitry::get('logger')->log($value);
    }

  function _T($translate)
{
return Zend_Registry::get('translator')->translate($translate);
}

Now all of these functions are global and you are free to call them from anywhere in your zf application . I do this with my every ZF project . Adding functions here for translation or logging purpose can be really time saver .

like image 32
Mr Coder Avatar answered Oct 23 '22 07:10

Mr Coder