Spiga

‘ zend framework ’ category archive

Multilanguage models in zend framework using Zend_Db_Table

January 20, 09 by Gabi Solomon

As i wrote in a previous post there are more ways to design a database for a multilanguage website, but the one i decided to go with is Coupled Translation table approach, where basicly for each table you have another one where you store a row for each language wich has the primary table id, language id and the other columns that need to be translated.

The Requirements and Implementation

Having this idea in mind i wrote a new class that extends Zend_Db_Table to provide an easy access to the translated tables. Basically the class a couple of things:
Read the rest of this entry »

Zend Framework View partial without reseting variables

January 18, 09 by Gabi Solomon

Important

Ignore this solution, there is already a solution in ZF implemented in View as Jani Hartikainen pointed out in the comment below.
Its $this->render('...');

Zend Framework has a view helper called partial that you can use to render other views in your view file.
This is very useful for reusing the html code.

The problem i sometimes faced with that partial helper is that it resets all the variables and you need to specify them as an array parameter if you want them to be available in the partial view rendered.

The solution

To overcome this all you need to do is make a new view helper ... i called mine GSD_View_Helper_Render witch extends the Zend_View_Helper_Partial and overwrites the methods that clones the view and resets the variables.

PHP:
  1. class GSD_View_Helper_Render extends Zend_View_Helper_Partial {
  2.  
  3.     public function cloneView()
  4.     {
  5.         $view = clone $this->view;
  6.         // $view->clearVars(); ... this was the line that resets all the variables.
  7.         return $view;
  8.     }
  9. }

Thats it. Hope this is of help to you.
Cheers

using Zend Framework Language component

December 15, 08 by Gabi Solomon

Today i will continue the series of articles on the zend framework and i am going to talk about how i come to use the language component from zend.

The way i decided to go with it is by having a controller plugin that starts the language component and also detects the language.

But first thing first. We need to make the url to allow us to change the language. And to do that i added a new rule in the bootstrap file:

PHP:
  1. $route = new Zend_Controller_Router_Route(
  2.             ':language/:controller/:action/*',
  3.                 array(
  4.                     'language'   => 'en',
  5.                     'module'     => 'default',
  6.                     'controller' => 'index',
  7.                     'action'     => 'index'
  8.                 )
  9.             );
  10.         $router->addRoute('lang_default', $route);

This rule will produce urls like:

http://www.domain.com/en/controller/action

http://www.domain.com/es/controller/action

I decided to go with this type of URL instead of caching or storing the language in the session to not have google consider our pages as duplicate content. I have read that it better to go with subdomains (ex: http://en.domain.com/controller/action ) that with directories but for now i will do it this way.

Now that we are still in the bootstrapfile, we will also add our plugin:

PHP:
  1. Zend_Controller_Front::getInstance()->registerPlugin(new GSD_Controller_Plugin_Language());

ANd now for the final touch the plugin:

PHP:
  1. <?php
  2.  
  3.  
  4.  
  5. /**
  6. * Front Controller Plugin
  7. *
  8. * @uses       Zend_Controller_Plugin_Abstract
  9. * @category   GSD
  10. * @package    GSD_Controller
  11. * @subpackage Plugins
  12. */
  13. class GSD_Controller_Plugin_Language extends Zend_Controller_Plugin_Abstract
  14. {
  15.        
  16.     public function routeShutdown(Zend_Controller_Request_Abstract $request)
  17.     {
  18.        
  19.         $locale = new Zend_Locale();
  20.        
  21.         $options = array('scan' => Zend_Translate::LOCALE_FILENAME);
  22.         $translate = new Zend_Translate('gettext', Zend_Registry::get('siteRootDir') . '/application/languages/', 'auto', $options);
  23.        
  24.         $requestParams = $this->getRequest()->getParams();
  25.         $language = (isset($requestParams['language'])) ? $requestParams['language'] : false;
  26.                 if ($language == false) {
  27.                      $language = ($translate->isAvailable($locale->getLanguage())) ? $locale->getLanguage() : 'en';
  28.                 }   
  29.         if (!$translate->isAvailable($language)) {
  30.             throw new Zend_Controller_Action_Exception('This page dont exist',404);
  31.         } else {
  32.        $locale->setLocale($language);
  33.             $translate->setLocale($locale);
  34.             
  35.             Zend_Form::setDefaultTranslator($translate);                                
  36.    
  37.            
  38.             setcookie('lang', $locale->getLanguage(), null, '/');
  39.             
  40.             Zend_Registry::set('Zend_Locale', $locale);
  41.             Zend_Registry::set('Zend_Translate', $translate);
  42.         }
  43.     }
  44. }

A few explanations on the code.
I am using gettext adapter with auto mode ... witch will basically crawl the language directory to detect what languages can you support. I also use it conjunction with Zend Locale and at the end i store the in the Registry.
Storing Zend translate in the registry will enable you to use it in the view in a very easy way using a built in helper.

Using translate in you controllers

PHP:
  1. $this->view->title = $this->view->translate('default-register-index-title');

Using translate in you views

PHP:
  1. <?php echo $this->translate('default-register-index-title'); ?>

As a note i am not using the full text for translate i am using keys that have a naming conventions like "module-controller-action-message". I find it much more easier then putting the whole string and also much more easier to maintain. Imagine if you misspelled a string, or want to modify it ? you will then have to modify it every in your code.

That is basically it.
Cheers

Update:
I have also published this plugin on phpclasses, you can find it here.

Zend Framework View Helper for Smarty Cycle

December 09, 08 by Gabi Solomon

As i stated in a recent post i am now starting to learn Zend Framework. And with all new things that you learn, you try to find the old ways ( at least i do :D ).

So today i was trying to find a method of creating a zebra table. The old way i used to this back when i was using smarty is by using the cycle custom function. Basically it will just alternate through a set of values to create the effect.

PHP:
  1. {section name=rows loop=$data}
  2. <tr bgcolor="{cycle values="#eeeeee,#d0d0d0"}">
  3.    <td>{$data[rows]}</td>
  4. </tr>
  5. {/section}

Then when i moved on and stop using smarty, i wrote a similar function for my template engine.

So now i am looking for a similar solution on Zend Framework. Luckily for me some bright fellows have already thought of me :D .
In the zend wiki there is a Zend_View_Helper_Cycle Component Proposal that does exacly what i was wishing for :D .

Heres an example of how you can use it:

PHP:
  1. <?php $cycle=$this->cycle(array("#F0F0F0","#FFFFFF"));?>
  2. <?php foreach ($this->books as $book):?>
  3.   <tr  style="background-color:<?=$cycle->next()?>">
  4.   <td><?=$this->escape($book['author']) ?></td>
  5. </tr>
  6. <?php endforeach;?>

The proposal has been approved for development in standard/incubator.
You can download it from here.

Cheers.

Zend Framework modular directory structure

December 01, 08 by Gabi Solomon

After a lot of thinking and going back and forth about this idea, i finally decided to start using ( learning at first ) zend framework.

The main decision was to go with an already built framework or an inhouse one. And although i really like reinventing the wheel sometimes, i said i will not do the same this time.

After deciding i wanted to use an exiting framework, i had 2 candidates in mind : CodeIgniter or zend framework. The plus for codeigniter was the fact that it went with a more familiar approach to MVC, and the plus for zend was the company behind it. The downside about zend, was for me at least, the size of it, and the fact that it seemed a lot to learn.

But i decided to take a chance and learn Zend. The main problem i had was how to start ( as all things are :D ). Because the have such a freedom in development, i was a little puzzled on how to structure my application.

The only thing i knew was that i wanted to go with a modular structure. From there i did a lot of googling, read and watched a few presentation about this topic and finaly came up with a structure wich is bassed much on Wil Sinclair proposal.

My Zend modular structure

I will try to explain it, why i chose it this way and what each folder contains.

1. Application

The main aplication folder
1.1 Config - Contains application configuration files ( ex: mysql details )
1.2 Controllers - General Controllers, that are common in all modules
1.3 Languages - Holds the language files
1.4 Layouts - This directory is for MCV based layouts.
1.5 Models - This directory holds the application models ( in put them here instead of the modules directory since i belive there are common to all application and its more better this way )
1.6 Modules - I really liked the idea of modules that zend used because it enables you to organize your controllers and views much better in a separate folder for different sections of a website ( for example the main website, editors area and admin panel )
1.7 Views - I also included a views folder in the main application because i though i could use it to store common views for the 3 modules.

2. Data

This folder holds various information that is temporary, like cache, session data etc.

3. Docs

This directory is for documentation automatically generated or hand written.

4. Library

This directory holds the library Zend Framework files and also other folders for your own library (extended from Zend or not). I have one called GSD that extends some zend classes.

5. Public

This directory would contain the public files for your application: index.php. index.php ( this will include the bootstrap.php file from your application/ directory) and the front end assets (css, javascript, images, flash etc )

6. Tests

This directory would hold the application tests. This is a cool feature about Zend that it has support for writing application tests to better test your code during development.

Final Words

Ok this is about it so far. I am still a beginer with zend, and this structure is what i have thought off so far, and it doesn't have some real application testing. Use it at your own expense :) )
I am sure as i start developing using zend that it will be modified.

Another bad thing about zend is that there aren't so much resources and real examples about it, this is why i will write about my journey with zend here. Hopefully somebody will benefit from it. :)

Cheers