Spiga

php adwords api library

December 25, 09 by Gabi Solomon

Recently i posted on google code a library we developed to interact with Adwords Api from php.
Php Adwords API Library was developed by Hyperactive team for an internal project, since we didn’t like options available and felt we could do something that would be easier to work with, at least for us. We made it public so that others looking for a php library to interact with adwords api would have more options to chose from ( plus free testing for us :-p ).

The project can be found here:
http://code.google.com/p/php-adwords-api/

It is still a work in progress and does not yet support all the services and functions of the API, but we hope to add more services as soon as possible. And if you need a certain service or function please dont hesitate to add a ticket on google code and request it.

You will find examples of usage in the folder examples of the library.

PDF Generation with Zend Framework

November 07, 09 by Gabi Solomon
Jonathan MaronGuest Post by:
Jonathan Maron has been working in the web application conceptualization and development space since 1996. His current position is with an international company, specialized in the production of word processing components. Being an advocate of the FOSS movement, Jonathan promotes the use of Open Source software and rejects the notion of reinventing the wheel, preferring to develop with established frameworks.

Generating print-ready well-formatted PDF documents with PHP is not an easy task. Traditionally, there are two main approaches to PDF generation with PHP. Given sufficient time and patience, both partially get the job done, but still leave a lot to be desired:

HTML-to-PDF: This approach is widely used in mainstream applications. Here an HTML document is programmatically created and converted to a PDF, using one of the many open source libraries 1. Since HTML, however, is not a page-oriented format (as is PDF), it is impossible to perform a 1-to-1 mapping between HTML and PDF. Typical word processing file format features, such as header and footers, orphans and widows or even page numbers can simply not be represented in HTML.
Read the rest of this entry »

MySQL Database versioning strategy

April 14, 09 by Gabi Solomon

IF you just got into versioning your code then you are probably really happy with your acomplishment.
But do you have your database versioned ? This is the questioned asked in this here by Jeff Atwood and also asked by a lot of users on stackoverflow.

After reading a lot on this topic i decided on a strategy on how to keep my database under version control.
As a warning it isn’t the most easy strategy and it really takes some discipline from all the developers.
Read the rest of this entry »

zend framework routing in models

February 08, 09 by Gabi Solomon

this post is more of a personal best practice and thought to share it with you guys. I like to do things this way, and think this is the best aproach, but i might be wrong and i would like your feedback on this :D .

So in Zend Framework first of all you are recommended to always use the routers assemble method to generate the Urls. Wich is very good since you will then have an easy way of updating an URL, for example when the SEO guy tells you to switch 2 url params around.

The problem is where you place your call to the router ?

One way to go about it is to place it in the controller, or in the view. But i think that is not the best ideea since this would mean in case you would want to change the route, the name for example, you would need to change it in all the places you made it.

A second choice would be to have the router call in a function somewhere that you would call from everywhere you would want the URL generated. But that seems to me like an extra layer.

My approch.

Almost all the time that URL is related to a model. For example if u have an article model. then you could make a method buildUrl :

PHP:
  1. public function buildUrl()
  2. {
  3.         $router = Zend_Controller_Front::getInstance()->getRouter();
  4.  
  5.         $url    = $router->assemble(
  6.                             array(
  7.                                 'article_id'    => $this->id,
  8.                             ),
  9.                             'article_page');
  10.         return $url;
  11. }

and then in your controllers and views you would just do:

PHP:
  1. $offer->buildUrl()

which looks nicer and you are keeping the call to the router in one place.

Thats about it, i know this might look like pretty simple stuff for most of you, but i hope some will find this useful.
Cheers

Optimizing Zend performance – small tip

January 29, 09 by Gabi Solomon

If you started working with Zend Framework you have notice that it is a bit slower then your regular php application.
This is due more or less to the double sword of having such a big framework to work with.

There are a lot of tips and tutorial out there on how to optimize your Zend Framework, and in all of them you will see the recommendation to remove the require_once from the library and to use Zend_Loader. Wich is a good advice since all those require_onces do put some stress on your application.

But after a bit of testing i camed to the conclusion that Zend_Loader isn't so fast. So i decided to go revert to a simple solution: writing my own autoloader.
I just put this small function at the top of my zend bootstrap file.

PHP:
  1. function __autoload($class) {
  2.     require str_replace('_', '/', $class) . '.php';
  3. }

And because i wrote all my application using Zend / Pear naming standard it works pretty good.

Hope you find this useful.
Cheers

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

php class for Unicode Manipulation

January 03, 09 by Gabi Solomon

If you ever had to build a site in a language that had special characters or a multilanguage website, then you have had problems with UTF encoding for sure.

Well recently a new class was published on phpclasses.org by Rubens Takiguti Ribeiro called Unicode Manipulation that will solve your problems.
The class is a complete solution to manipulate Unicode encoded text with support for UTF-16 and UTF-32 besides UTF-8.

This class can be used to manipulate text with Unicode encodings.

It can perform several types of operations that involve text strings encoded as UTF-8, UTF-16 or UTF-32, like:

- Get the text sequence for byte order mark for little and big endian
- Convert a given character code to Unicode encoded text and vice-versa
- Get the byte length of a given Unicode encoded character
- Convert text encoding between UTF-8, UTF-16 and UTF-32
- Get a part of an Unicode encoded string from a given position and an optional length
- Get the string length of an Unicode encoded text
- Determine whether a given string has Unicode encoded text

[Class Page]

Hope you find it usefull,
Cheers.

Netbeans review

December 15, 08 by Gabi Solomon

There seems to be quite a few talks about netbeans these days. A lot of people blogged about it and sayd its the next big thing or something. I personally tested it a while ago, like 4-5 months i think, i dont remember exaclly what made me drop it so i said i must try this new version to see what all the fuss is about.

Now before i start, i want to give you a heads up :) . I am a big fan of zend studio, (am using 5.5, hate the 6 series) and all its features, so when i test a new editor i tend to compare it to zend. I know its not free and it really inst the cheapest editor, but i was lucky enough (or good enough, if i wasn't this modest) to win it as a prize at the Innovation Award on phpclasses.com.

Now back to NetBeans.

The first thing u should know is that its free. And this always counts as a big plus for any software.

As far as the interface is concerned, i like very much. Its very intuitive and simple to use. You have the general layout with projects on the left, content editor with all the basic features: tabs, sintax highlight, php code assist.
The first plus for netbeans would be the support for html, css, javascript and all the major javascript frameworks. Wich for some people count very much. This is something i admit i miss in Zend. There is a small support for html but that is it.

Another cool feature are the snippets (they caled them templates), this is when you tipe in class and it can automplete a basic class code for you. This templates can be edited so you can add any code snippet that u use very often here for faster writing.

I found that it has the functionality i didnt find in other editor except zend before. Things like :
- code assist for you own functions and classes
- really good code folding (some IDEs tend to get confused and have bad code folding)
- opening the file that contains the function/method on CTRL+click on the name (or any mouse + keyboard combination)

via http://codeutopia.net/

via http://codeutopia.net/

Altough some might disagree about the importance of these functions, i think they are crucial when working on big projects. I tend to forget where a function is on my projects after a while of not working on it, much more when it comes to projects running a script that is not coded by me. So the persons that don't think that is necessary ... try modifying lets say a magento powered store. Lets see how you find where a function is declared, and how much time you loose on this task.

So all these put together really made me think of switching to netbeans.
So i really gave it a try and started to use it to code a project.

I found that it is really great to work with, and personally it seemed a little faster then zend on loading times (sometimes zend would freeze a little on ALT+TAB).

Also found new features that i didn't find in Zend, that really were nice to have:
- Refactoring ( you can rename a variable or a method in your class and it gets renamed whereever its used in your project )
- ToDo list ( it has a small tab where it parses the files for TODO comment lines and shows them in that tab)
- phpdoc comments code assist
- a really nice debuger that integrates with Xdebug
- code assist offers a link to php website for the php functions
- support for CVS, Subversion and Mercurial

The bad side

At this point i was 95% convinced of switching to netbeans. But then it let me down. The Ftp support really sucked. This is another must have feature for me.
I am used of working on remote servers, dont really enjoy working localy. So i want a verry good FTP client in my IDE. I enjoy the way Zend has done it. You just add a ftp server and your done ... you can edit the files at will as if they were localy, you dont care how he downloads them makes the a temporary file etc. As soon as you hit Save the files gets uploaded to the server.

The way that netbeans does it is by downloading all the files localy at first, work on them locally and when you hit RUN in the IDE the ones modified gets transferred to the server. Wich might work when your developing a project on your own ... but when you develop with a team its just not going to work. Or even if your alone, but you just want to do some quick modification to a website that is online, its going to take a while to setup the project in netbeans.

I found a workaround to this problem, you could use an automatic syncronization tool like Fling to do the synk between the files online and the ones locally. But you must be carefull how you setup it so you don't overwrite others coworkers modification on the project.

Another smaller issue in netbeans is the file path. If your working on a file it doesnt show you the path of that file. So you dont know on wich file your actualy working since many times files have the same names either in diferent components of the same project or you can mistakenly edit the same file from a diferent project. It does display it as a tool tip on the tabs name but the best way i see this done is in the application title bar.

Conclusion

I agree that Netbeans is a great IDE and it has a lot of features, even ones i cant find in Zend, and if your a javascript developer thant this would be right for you. But until they redo the FTP client or someone writes a better FTP plugin, i cant use it. So i am stuck with Zend again :D
Altough i will be following the evolution of netbeans and maybe switch when they will have a better ftp support.

Cheers

using Zend Framework Language component

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.

determining the application root path and url in php

December 13, 08 by Gabi Solomon

If you buid any web application you will eventually need to find a way to specify the application root path and URL. This is inevitable if you don't build your links in a relative way ( by unsing ./ and ../ combinations ), and also if you want to have a way of keeping things organized and working even if you move script to a new server or in a folder.

Well there are several ways you can do this. The first one would be to write them in a config file by hand, and edit them as you move the project.

PHP:
  1. define('ROOT_PATH', '/home/user/public_html/folder/');
  2. define('PROJECT_DIR', '/folder/');
  3. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

But even if that works well, it will give a bit of work when you move the application since you have to edit them by hand.
So the next method would be to have them be generated automatically. The ROOT_PATH is relatively easy to determine . What i do is have a directory called config in wich i place my config files, in it i have one called main_config.php which includes the rest of the config files. One of them is called paths.php.
Now to determine the root_path i use a function called dirname() and the __FILE__ constant.

PHP:
  1. define('ROOT_PATH', dirname(dirname(__FILE__)));
  2. define('PROJECT_DIR', '/folder/');
  3. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

Now we have the root_path solved and base_url to some extend, but need to specify the project directory.
We can solve that too automatically.

PHP:
  1. define('ROOT_PATH', '/home/user/public_html/folder/');
  2. $projectDir = implode('/', array_intersect(explode('/', $_SERVER["REQUEST_URI"]), explode('/', str_replace('\\', '/', ROOT_PATH))));
  3. if ($projectDir[strlen($projectDir)-1] != '/') {
  4.         $projectDir .= '/';
  5. }
  6. define('PROJECT_DIR', $projectDir);
  7. define('BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . PROJECT_DIR);

What that code does is take the ROOT_PATH that we defined and the REQUEST_URI from the server global variable and do an intersection of them to determine the project dir.

Hope this small snippet helped you.
Cheers