stoimen.com/blog

web developing

Archive for the ‘zend framework’ Category

In most of the tutorials about Zend Framework the simple theory is described how all these MVC things may work together. However beyond that the things become more and more tricky and not everything is done by the MVC pattern itself.

What I mean is that reading most of the tutorials about ZF I found describing the simple relationship between controllers and views just by setting up a view member variable in the controller and than simply call that variable in the view of that particular controller action.

Setup controller’s view variable. In this example I used the default ZF IndexController – indexAction:

public IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->greeting = ‘Hello World!’;
    }
}

where afterwards you can call this member variable in the index.phtml view in the index view scripts.

Note: In a typical Zend Framework installation all this is setup into the application folder (either web visible or not), where the IndexController.php file containing the code above is placed into the application/controllers and its indexAction stores its view in the application/views/scripts/index/index.phtml

In that situation the view file, the previously mentioned index.phtml should access this “greeting” variable in something like:

<div><?php echo $this->greeting ?></div>

Note that here you miss the ->view-> part of the chain. That’s because the view’s parsed and now this contains everything that the controller’s view member object contains.

All that is pretty cool and it works great until you start accessing and working with different type of data escaped or not, coming from various sources.

Natively comes the problem of escaping bad strings and the single question is why should I do that? To give you a simple example I’ll describe the above code in a different manner.

Imagine you should setup a browser specific title depending of the controller/action you call. To do that is simple but there comes the tricky part. In the example above we can just change the code a bit.

In the controller you can setup the browserTitle variable:

<?php
class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->browserTitle = “Welcome”;
    }
}

Than normally in the view you may have something like that:

<html>
<head>
<title><?php echo $this->browserTitle ?></title>
...

Everything until that looks normal and you don’t need to escape whatever as it appears. Even if the browserTitle contains something with quotes:

...
$this->view->browserTitle = ‘Hello ”World”’;
...

This will result in the browser’s source view as:

...
<title>Hello “World”</title>
...

see the image below:


But what if you setup a meta title tag:

<meta name=”title” content=”Hello “World”” />

for the browser that’s an error as shown on the image:

There’s why you simply should be careful when dumping variables all over the page and to use the native ZF escape function.

$this->escape()

In the example above you simply can call the escape function into the view:

<html>
<head>
<title><?php echo $this->browserTitle ?></title>
<meta name=”title” content=”<?php echo $this->escape($this->browserTitle) ?>” />

That will prevent the browser to “crash” and of course and more important will improve the site’s SEO.

Although it may sound strange I’ll say why I’m using caching. Because it speeds up the site! Yeah there’s no other reason that may be so important as this is.

The caching is not a process invented in the last year, it’s useless to describe why do you need it, but however my intention is to describe how to make it work with Zend Framework.

The docs page of Zend_Cache is pretty clear about everything and I’ll describe the most important part of the cache setup.

First setup the cache back and frontend options. You need to decide where to save the cache files, how to cache them, and what lifetime do they need.

The most used cache configuration is, as you may guess, this one described into the doc page. Setup the front and backend options is just as simple as:

$frontendOptions = array(
     'lifetime' => 7200, // cache lifetime of 2 hours
     'automatic_serialization' => true
);

$backendOptions = array(
   'cache_dir' => './tmp/'
   // Directory where to put the cache files
);

// getting a Zend_Cache_Core object
$cache = Zend_Cache::factory('Core',
                             'File',
                              $frontendOptions,
                              $backendOptions);

Because all this is well described into the doc page, which you can found here I won’t talk about it. But I’ll talk only about one sole thing. How much the cache must live? What should be its lifetime.

The answer is simple. If you have some basic statistic of your site traffic and you don’t change much the data you can prefer longer cache period. But imagine the site’s making 1000 visits per minute! Than even if you cache every minute and the cache expires every minute will be a success and the user perception will be really great. From those 1000 visitors only few will wait until the cache’s built and the other hundreds will receive really fast response!

Be careful when you cache only because you can overflow the directory where you cache, which will be difficult though.

In other way many people are thinking about Zend Optimizer and its work with Zend_Cache. These are really different things. Zend Optimizer has nothing to do with your code it is a PHP caching tool. As you may know PHP interpreter mingles the code into “machine like” code, which in turn can be cached into the RAM with the help of Zend Optimizer. Checkout more here.

  • 0 Comments
  • Filed under: zend framework
  • When I say better documentation I don’t mean it was somehow bad before. The difference is that now the doc pages are version specific, and this is particularly good for those working with older versions of the framework.

    In fact most of the cases are just like that, whether because it’s difficult to migrate some code that’s already too different from the original framework itself or because the new version is considered “not so stable”.

    Whatever the reason is the version specific docs will be received very well from the community.

  • 0 Comments
  • Filed under: zend framework
  • What are validators?

    In very very breve these are methods which can validate some data, usually user input, against some specific rules. Imagine there’s a web form that is always checked for empty fields or some fields that may contain valid e-mail addresses. This is so common that became everyday routine to almost all of us. However smart developers make abstractions that help them reuse all this functionality. Even smarter developers make use of frameworks. And for those of you, using Zend Framework, there’s no need to write most of the common used validators, simply because they come with the framework itself.

    Technically you’ve various validators in zend, such as Zend_Validate_Alnum, Zend_Validate_Email or Zend_Validate_Regex. All these are extremely useful when it comes to automatic, bullet proof validation, but I’m going to talk more about one specific validator.

    Zend_Validate_Db_RecordExists

    Although the implementation is nothing more than just a chunk of code and doesn’t pretend to be difficult, the idea of such validator is genius indeed. It really helps you do some amazing job.

    Image you have to check some database record existence. Then comes in help this validator. In fact I’m pretty sure almost everyone has experience with such kind of task. Simply because the registration process almost always requires it. When you try to register new user you more often check for the username existence. Although you may solve the problem with other technique by catching the exception the database is throwing for duplicate entries, this should be assumed just as an example.

    I’m pretty sure this validator can be really useful in many occasions!

  • 0 Comments
  • Filed under: zend framework
  • Although the documentation of Zend Framework is one of the most well structured documentation I’ve ever read it happened to me to stuck into it. And that happened exactly when I tried to use the date component of ZF – Zend_Date.

    Why I’d prefer Zend_Date?

    We all know what the date function of PHP is, and what it does. It has reach set of formating string that help you do the job but as I’m working mostly on multilingual projects almost every project needs multilingual dates, and more or less nobody wants only numbers into the dates. And all this is pretty natural, instead of using the simple

    01.01.2010

    format, which beside it’s natural ugliness is not clear. Because as you may know in the US this can be understood as month.date.year, while in Europe this is date.month.year. And when it comes to dates like 02.01.2010 this can be really frustrating.

    Beside this ugly format, you can choose to format your dates either with:

    1 January 2010 or 1 Jan 2010

    which is clear enough, but it’s only for english speakers. You know that in a spanish speaking country you should format the same date as:

    1 Ene 2010

    where “ene” means enero – january in spanish. How should you overcome this natural PHP problem?

    Well the answer is by using Zend_Date

    The problem I found in Zend_Date usage is that the native copy/paste technique from the doc page doesn’t seem to work. What the doc page says you is:

    // setup the default timezone
    date_default_timezone_set('Europe/London');

    and than you can simply request a date with:

    $date = new Zend_Date(‘2010-01-02’);
    echo $date->get('d MMM yyyy');

    where this should print 1 Jan 2010.

    It’s a shame that this doesn’t work. The good part is that this problem can be overcome very simply. You just need to setup some more things just before calling the get method.

    First setup a cache mechanism where you can cache the date locales. This is really good practice because it speeds up the framework when dealing with dates. Just add those lines after the default timezone is set:

    // setup the default timezone
    date_default_timezone_set('Europe/London');
    
    $locale = new Zend_Locale(‘es_ES’);
    Zend_Registry::set('Zend_Locale', $locale);
    
    $frontendOptions = array(
    		'lifetime' => 600, // 10 minutes
    		'automatic_serialization' => true
    );
    
    $backendOptions = array(
                    'cache_dir' => '../cache/'
    		);
    
    // getting a Zend_Cache_Core object
    $cache = Zend_Cache::factory('Core',
    		             'File',
    		              $frontendOptions,
    		              $backendOptions);

    First you setup the Zend_Locale – a locale for the entire application and set it up in this example for spanish, than setup the cache mechanism.

    This is a typical cache setup for Zend Framework. If you’d like to dive more into cacheing you can checkout the doc pages for Zend_Cache.

    After these lines just setup Zend_Date options with:

    Zend_Date::setOptions(array('format_type' => 'php',
                       'cache' => $cache));

    This is really what you need to do to start. All these lines of code you may place into the bootstrap.php or into some front controller plugin.

    Then you can call Zend_Date’s get method wherever you’d like in every controller you need it!

  • 0 Comments
  • Filed under: zend framework