Category Archives: PHP - Page 8

Redirection in Zend Framework

Quite often you need to redirect to another controller/action after a decision in the controller. Sometimes you need to redirect to a whole different site. This is how I do redirects in Zend Framework 1.10:

Redirect to another controller and/or action
For this I use the Zend_Controller_Action_Helper function redirector(action, controller name)

$this->_helper->redirector('display', 'index');

This will redirect to the displayAction in the indexController

Redirect to another site
For this I use the Zend_Controller_Action function redirect(url). The redirect function takes an full url as input (you can also supply an array with redirect options)

$this->_redirect('http://framework.zend.com/');

This will redirect you to the Zend Framework site

How to make a custom validator:CheckIfEmailIsUnique

Today I will talk about making custom validators in Zend Framework 1.10. Sometimes you need to validate something special that the standard built-in validators can not handle. This is the perfect time to make your own.

Custom validators are placed in the library section. In this example I put my new validator here: Library/My/Validator/CheckIfEmailIsUnique.php

class My_Validator_CheckIfEmailIsUnique extends Zend_Validator_Abstract {

    // Init error message variable
    const MSG_EMAIL_ALREADY_EXISTS = ""; 

    // Set error msg in the message template (%value% will be replaced with indata email)
    protected $_messageTemplates = array(
        self::MSG_EMAIL_ALREADY_EXISTS => "'%value%' is already in use. Please choose another",
    );
    // The only function we need to write is isValue
    public function isValid($email) {

        // This will replace the %value% with the tested email address in the error msg
        $this->_setValue($email);

        // Get the model
        $model = new Application_Model_Validator();
        // Run the unique test in the model 
        if($model->checkIfEmailIsUnigue($email)){
           // Email is unique in the database - return true
           return true;
        }
        else {
            // Email is not unique
            //Set error message
            $this->_error(self::MSG_EMAIL_ALREADY_EXISTS);
            // Return false
            return false;
        }
    }
}

To check if the email is unique I made a function in my validator model that checks the email agains those already in the database. If it finds the email it will return false and if not true

Application/Model/Validator.php

class Application_Model_Validator {

    public function  __construct() {
        $this->_db = Zend_Registry::get('db');
    }

    public function checkIfEmailIsUnique($email) {

        $query ="SELECT id FROM user WHERE email = '{$email}'";

        $result = $this->_db->fetchOne($query);

        if(!$result){
            return true;
        }
        else {
            return false;
        }
    }
...
}

Now all we need to do is to add the new validator to our Zend_Form. We do this by first adding the path to the new validator (My/Validator/) and then add the new validator with the Zend_Element addValidator() function (the same way you add the built in validators).

Application/Forms/CreateAccount.php

class Application_Form_CreateAccount extends Zend_Form {
...
    public function init() {

        //Add path to custom validators - IMPORTANT
        $this->addElementPrefixPath('My_Validator', 'My/Validator/', Zend_Form_Element::VALIDATE);

        $email = new Zend_Form_Element_Text('email');
        $email->setLabel('E-mail:')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim')
                ->addValidator('EmailAddress', true)
                ->addValidator('CheckIfEmailIsUnique');//Here I add the new validator
...
        }
}

Since I do not validate the email format in my new validator I use the built-in validator EmailAddress and set the second argument to true. This means that if the EmailAddress validator returns false our CheckIfEmailIsUnique will not be run at all. The element will return the error and stop executing.

Hope this will help you understand how to make your own custom validators in Zend Framework

Accessing custom values from your Application.ini anywhere in your application using Zend_Registry

In most applications you need to have some settings that control how the application will behave. Variables that can be changed to tweak how some specific thing is handled. In Zend Framework 1.10 this is pretty straightforward. I’m here going to show you how I solved this problem. I’m sure there are many ways to accomplish this but this is the way I used.

You create your custom variables in your Application.ini

; DB Settings
resources.db.adapter = PDO_MYSQL
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = secret
resources.db.params.dbname = gamedb

; My Settings
GameSettings.startCredits = 100
GameSettings.startPos.y = 288
GameSettings.startPos.x = 10

; Misc Settings
resources.frontController.params.displayExceptions = 0
resources.view.helperPath = APPLICATION_PATH “/views/helpers”
phpSettings.date.timezone = "Europe/London"

and then you use the Zend_Registry to make the config settings available anywhere in your application by adding the following code to your Bootstrap.php

protected function _initConfig() {

        Zend_Registry::set('config', $this->getOptions());

}

In your application model, controller or view you can now access your settings like this:

//Get config values
$config = Zend_Registry::get('config');

$startCredits  = $config['GameSettings']['startCredits'];
$startPosY     = $config['GameSettings']['startPos']['y'];
$startPosX     = $config['GameSettings']['startPos']['x'];

You can also include the config object in you init() method to have it easily accessible in your class

class MyClass extends Zend_Something {

       protected $_gameSettings = array();

       public function init() {

               $config = Zend_Registry::get('config');

               $this->_gameSettings = $config;

       }
...
}