Archive for May, 2014


As a Zend Framework 1 user I loved the simplicity of the class naming convention, being Folder_Subfolder_ClassName. However as you probably know, these class names get really quite long! The latest PHP as you already know uses namespaces and allows for shorter classnames that wont clash with each other. Now I have added an API to my website using the incredible Apigility (http://apigility.org) which was built in Zend Framework 2, I thought it would be nice to upgrade my existing classes to autoload PSR-0 style, so I can eventually migrate easily across.

First thing then, you need composer installed. If you’ve been following my blog, or using any other vendors packages, you’ll already have it in your project.

In ZF1, the library folder was where you would keep your different modules/packages/classes. I have a library called TTB. So in the TTB folder, create an src folder, and another TTB folder in there (this is a quirk of PSR-0, but trust me). In that folder, recreate your classes. Changes aren’t very difficult:

<?php
namespace TTB\Form;
use TTB\Form\Element;

class Contact extends \Zend_Form
{
    //etc
}

The line TTB_Form_Contact extends Zend_Form is shortened by way of the namespace line at the top to just become Contact, and the Zend_Form gets a backslash in front of it as it is in the global namespace. You also specify use  to import any other classes into the namespace. Now we can call Textbox instead of Element\Textbox or TTB\Form\Element\Textbox.

You probably know all this stuff anyway! The point is, to get it autoloading in your project!

So in your index file of your ZF1 project, require once vendor/autoload.php. And in your composer.json, add the following:

"autoload": {
     "psr-0": {
         "TTB" : "application/library/TTB/src/"
     }
 }

Finally, run composer dump-autoload in the terminal from your site root, and this will generate the classmap. You are now ready for PSR-0 compliance! Now you just need to spend all day refactoring! It’ll be worth it when you take your old project to a new framework!  😉

Advertisements

I had this weird problem today where my API was working fine on the development machine, but on my production server I was getting a blank 200 text/html page.

It turned out that the array that was being changed into JSON contained certain characters which were not UTF-8, meaning that a var_dump($json) returned bool : false.

I found a nice class on github which has some static methods for doing a bunch of utf-8 character encoding fixes. Feeding my array into the fixUtf8() method sorted everything!

https://github.com/neitanod/forceutf8

<?php
/*
Copyright (c) 2008 Sebastián Grignoli
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
“AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author “Sebastián Grignoli” <grignoli@framework2.com.ar>
* @package Encoding
* @version 1.2
* @license Revised BSD
*/
namespace ForceUTF8;
class Encoding {
  protected static $win1252ToUtf8 = array(
        128 => \xe2\x82\xac,
        130 => \xe2\x80\x9a,
        131 => \xc6\x92,
        132 => \xe2\x80\x9e,
        133 => \xe2\x80\xa6,
        134 => \xe2\x80\xa0,
        135 => \xe2\x80\xa1,
        136 => \xcb\x86,
        137 => \xe2\x80\xb0,
        138 => \xc5\xa0,
        139 => \xe2\x80\xb9,
        140 => \xc5\x92,
        142 => \xc5\xbd,
        145 => \xe2\x80\x98,
        146 => \xe2\x80\x99,
        147 => \xe2\x80\x9c,
        148 => \xe2\x80\x9d,
        149 => \xe2\x80\xa2,
        150 => \xe2\x80\x93,
        151 => \xe2\x80\x94,
        152 => \xcb\x9c,
        153 => \xe2\x84\xa2,
        154 => \xc5\xa1,
        155 => \xe2\x80\xba,
        156 => \xc5\x93,
        158 => \xc5\xbe,
        159 => \xc5\xb8
  );
    protected static $brokenUtf8ToUtf8 = array(
        \xc2\x80 => \xe2\x82\xac,
        \xc2\x82 => \xe2\x80\x9a,
        \xc2\x83 => \xc6\x92,
        \xc2\x84 => \xe2\x80\x9e,
        \xc2\x85 => \xe2\x80\xa6,
        \xc2\x86 => \xe2\x80\xa0,
        \xc2\x87 => \xe2\x80\xa1,
        \xc2\x88 => \xcb\x86,
        \xc2\x89 => \xe2\x80\xb0,
        \xc2\x8a => \xc5\xa0,
        \xc2\x8b => \xe2\x80\xb9,
        \xc2\x8c => \xc5\x92,
        \xc2\x8e => \xc5\xbd,
        \xc2\x91 => \xe2\x80\x98,
        \xc2\x92 => \xe2\x80\x99,
        \xc2\x93 => \xe2\x80\x9c,
        \xc2\x94 => \xe2\x80\x9d,
        \xc2\x95 => \xe2\x80\xa2,
        \xc2\x96 => \xe2\x80\x93,
        \xc2\x97 => \xe2\x80\x94,
        \xc2\x98 => \xcb\x9c,
        \xc2\x99 => \xe2\x84\xa2,
        \xc2\x9a => \xc5\xa1,
        \xc2\x9b => \xe2\x80\xba,
        \xc2\x9c => \xc5\x93,
        \xc2\x9e => \xc5\xbe,
        \xc2\x9f => \xc5\xb8
  );
  protected static $utf8ToWin1252 = array(
       \xe2\x82\xac => \x80,
       \xe2\x80\x9a => \x82,
       \xc6\x92 => \x83,
       \xe2\x80\x9e => \x84,
       \xe2\x80\xa6 => \x85,
       \xe2\x80\xa0 => \x86,
       \xe2\x80\xa1 => \x87,
       \xcb\x86 => \x88,
       \xe2\x80\xb0 => \x89,
       \xc5\xa0 => \x8a,
       \xe2\x80\xb9 => \x8b,
       \xc5\x92 => \x8c,
       \xc5\xbd => \x8e,
       \xe2\x80\x98 => \x91,
       \xe2\x80\x99 => \x92,
       \xe2\x80\x9c => \x93,
       \xe2\x80\x9d => \x94,
       \xe2\x80\xa2 => \x95,
       \xe2\x80\x93 => \x96,
       \xe2\x80\x94 => \x97,
       \xcb\x9c => \x98,
       \xe2\x84\xa2 => \x99,
       \xc5\xa1 => \x9a,
       \xe2\x80\xba => \x9b,
       \xc5\x93 => \x9c,
       \xc5\xbe => \x9e,
       \xc5\xb8 => \x9f
    );
  static function toUTF8($text){
  /**
* Function Encoding::toUTF8
*
* This function leaves UTF8 characters alone, while converting almost all non-UTF8 to UTF8.
*
* It assumes that the encoding of the original string is either Windows-1252 or ISO 8859-1.
*
* It may fail to convert characters to UTF-8 if they fall into one of these scenarios:
*
* 1) when any of these characters: ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß
* are followed by any of these: (“group B”)
* ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶•¸¹º»¼½¾¿
* For example: %ABREPRESENT%C9%BB. «REPRESENTÉ»
* The “«” (%AB) character will be converted, but the “É” followed by “»” (%C9%BB)
* is also a valid unicode character, and will be left unchanged.
*
* 2) when any of these: àáâãäåæçèéêëìíîï are followed by TWO chars from group B,
* 3) when any of these: ðñòó are followed by THREE chars from group B.
*
* @name toUTF8
* @param string $text Any string.
* @return string The same string, UTF8 encoded
*
*/
    if(is_array($text))
    {
      foreach($text as $k => $v)
      {
        $text[$k] = self::toUTF8($v);
      }
      return $text;
    } elseif(is_string($text)) {
      $max = strlen($text);
      $buf = “”;
      for($i = 0; $i < $max; $i++){
          $c1 = $text{$i};
          if($c1>=\xc0){ //Should be converted to UTF8, if it’s not UTF8 already
            $c2 = $i+1 >= $max? \x00 : $text{$i+1};
            $c3 = $i+2 >= $max? \x00 : $text{$i+2};
            $c4 = $i+3 >= $max? \x00 : $text{$i+3};
              if($c1 >= \xc0 & $c1 <= \xdf){ //looks like 2 bytes UTF8
                  if($c2 >= \x80 && $c2 <= \xbf){ //yeah, almost sure it’s UTF8 already
                      $buf .= $c1 . $c2;
                      $i++;
                  } else { //not valid UTF8. Convert it.
                      $cc1 = (chr(ord($c1) / 64) | \xc0);
                      $cc2 = ($c1 & \x3f) | \x80;
                      $buf .= $cc1 . $cc2;
                  }
              } elseif($c1 >= \xe0 & $c1 <= \xef){ //looks like 3 bytes UTF8
                  if($c2 >= \x80 && $c2 <= \xbf && $c3 >= \x80 && $c3 <= \xbf){ //yeah, almost sure it’s UTF8 already
                      $buf .= $c1 . $c2 . $c3;
                      $i = $i + 2;
                  } else { //not valid UTF8. Convert it.
                      $cc1 = (chr(ord($c1) / 64) | \xc0);
                      $cc2 = ($c1 & \x3f) | \x80;
                      $buf .= $cc1 . $cc2;
                  }
              } elseif($c1 >= \xf0 & $c1 <= \xf7){ //looks like 4 bytes UTF8
                  if($c2 >= \x80 && $c2 <= \xbf && $c3 >= \x80 && $c3 <= \xbf && $c4 >= \x80 && $c4 <= \xbf){ //yeah, almost sure it’s UTF8 already
                      $buf .= $c1 . $c2 . $c3;
                      $i = $i + 2;
                  } else { //not valid UTF8. Convert it.
                      $cc1 = (chr(ord($c1) / 64) | \xc0);
                      $cc2 = ($c1 & \x3f) | \x80;
                      $buf .= $cc1 . $cc2;
                  }
              } else { //doesn’t look like UTF8, but should be converted
                      $cc1 = (chr(ord($c1) / 64) | \xc0);
                      $cc2 = (($c1 & \x3f) | \x80);
                      $buf .= $cc1 . $cc2;
              }
          } elseif(($c1 & \xc0) == \x80){ // needs conversion
                if(isset(self::$win1252ToUtf8[ord($c1)])) { //found in Windows-1252 special cases
                    $buf .= self::$win1252ToUtf8[ord($c1)];
                } else {
                  $cc1 = (chr(ord($c1) / 64) | \xc0);
                  $cc2 = (($c1 & \x3f) | \x80);
                  $buf .= $cc1 . $cc2;
                }
          } else { // it doesn’t need convesion
              $buf .= $c1;
          }
      }
      return $buf;
    } else {
      return $text;
    }
  }
  static function toWin1252($text) {
    if(is_array($text)) {
      foreach($text as $k => $v) {
        $text[$k] = self::toWin1252($v);
      }
      return $text;
    } elseif(is_string($text)) {
      return utf8_decode(str_replace(array_keys(self::$utf8ToWin1252), array_values(self::$utf8ToWin1252), self::toUTF8($text)));
    } else {
      return $text;
    }
  }
  static function toISO8859($text) {
    return self::toWin1252($text);
  }
  static function toLatin1($text) {
    return self::toWin1252($text);
  }
  static function fixUTF8($text){
    if(is_array($text)) {
      foreach($text as $k => $v) {
        $text[$k] = self::fixUTF8($v);
      }
      return $text;
    }
    $last = “”;
    while($last <> $text){
      $last = $text;
      $text = self::toUTF8(utf8_decode(str_replace(array_keys(self::$utf8ToWin1252), array_values(self::$utf8ToWin1252), $text)));
    }
    $text = self::toUTF8(utf8_decode(str_replace(array_keys(self::$utf8ToWin1252), array_values(self::$utf8ToWin1252), $text)));
    return $text;
  }
  static function UTF8FixWin1252Chars($text){
    // If you received an UTF-8 string that was converted from Windows-1252 as it was ISO8859-1
    // (ignoring Windows-1252 chars from 80 to 9F) use this function to fix it.
    return str_replace(array_keys(self::$brokenUtf8ToUtf8), array_values(self::$brokenUtf8ToUtf8), $text);
  }
  static function removeBOM($str=“”){
    if(substr($str, 0,3) == pack(“CCC”,0xef,0xbb,0xbf)) {
      $str=substr($str, 3);
    }
    return $str;
  }
  public static function normalizeEncoding($encodingLabel)
  {
    $encoding = strtoupper($encodingLabel);
    $enc = preg_replace(‘/[^a-zA-Z0-9\s]/’, , $encoding);
    $equivalences = array(
        ‘ISO88591’ => ‘ISO-8859-1’,
        ‘ISO8859’ => ‘ISO-8859-1’,
        ‘ISO’ => ‘ISO-8859-1’,
        ‘LATIN1’ => ‘ISO-8859-1’,
        ‘LATIN’ => ‘ISO-8859-1’,
        ‘UTF8’ => ‘UTF-8’,
        ‘UTF’ => ‘UTF-8’,
        ‘WIN1252’ => ‘ISO-8859-1’,
        ‘WINDOWS1252’ => ‘ISO-8859-1’
    );
    if(empty($equivalences[$encoding])){
      return ‘UTF-8’;
    }
    return $equivalences[$encoding];
  }
  public static function encode($encodingLabel, $text)
  {
    $encodingLabel = self::normalizeEncoding($encodingLabel);
    if($encodingLabel == ‘UTF-8’) return Encoding::toUTF8($text);
    if($encodingLabel == ‘ISO-8859-1’) return Encoding::toLatin1($text);
  }
}

							

If you checked my last post, you will have read about how to get all your old ZF1 classes autoloading in your new shiny ZF2 project. However, the DB settings from your application.ini won’t have been set, and so you’ll get a 500 response with  No Db Adapter. Not a problem. We just create the db adapter ourselves and tell Zend_Db that it is the default.

I’ve put this in the ZF2 index.php just before the last line, Zend\Mvc\Application::init($appConfig)->run();

//Set up ZF1 DB
$params = array(
 'host' => '127.0.0.1',
 'username' => 'xxx',
 'password' => 'xxx',
 'dbname' => 'xxx'
);
$adapter = Zend_Db::factory('Pdo_Mysql',$params);
Zend_Db_Table_Abstract::setDefaultAdapter($adapter);

Now your autoloading ZF1 DB classes wont freak out, and should connect no problem!

I’ve started using Apigility for building my API for my mobile app of my site! It’s incredible, you have to try it!

Anyway, I wanted to be able to load my existing code into ZF2 so I didn’t have to reinvent the wheel.

My API is running on a subdomain in an api sub folder within the main project. In the api folder, I made a folder called library. Then I symlinked my Zend and other folders from my ZF1 project into it (this may not have been necessary, but I didn’t want ../.. relative link type stuff in my composer.json)

:~/www/site/api/library$ ln -s ../../application/library/Zend Zend
:~/www/site/api/library$ ln -s ../../application/library/ZendX ZendX
:~/www/site/api/library$ ln -s ../../application/library/TTB TTB
:~/www/site/api/library$ ln -s ../../application/library/AA AA

Next you need to do is tell composer.json about your libraries.

 "autoload": {
 "psr-0": {
 "AA_": "library/",
 "Zend_": "library/",
 "ZendX_": "library/"
 }
 },
 "include-path": [
 "library"
 ]

Finally get composer generating autoload files. Type in:

~/www/site/api$ composer dump-autoload
Generating autoload files

And thats it! You should now be able to call things like:

$awesome = new Zend_Pdf();
$old_skool = new AA_Old_Skool_Class();

Yay!

There’s a stack of different icon sizes and splash screen sizes now, depending which iPod, iPhone, or iPad you are using. iPad can also splash screen in Landscape, iPhone 5 has a different aspect ratio, etc! It has been a while since I last made web app icons etc, so I brought myself up to speed, and found the following Gist on Github:

Very handy 🙂

<!– Run in full-screen mode. –>
<meta name=“apple-mobile-web-app-capable” content=“yes”>
<!– Make the status bar black with white text. –>
<meta name=“apple-mobile-web-app-status-bar-style” content=“black”>
<!– Customize home screen title. –>
<meta name=“apple-mobile-web-app-title” content=“Web App”>
<!– Disable phone number detection. –>
<meta name=“format-detection” content=“telephone=no”>
<!– Set viewport. –>
<meta name=“viewport” content=“initial-scale=1”>
<!– Prevent text size adjustment on orientation change. –>
<style>html { webkittextsizeadjust: 100%; }</style>
<title>iOS 7 Web App</title>
<!– Icons –>
<!– iOS 7 iPad (retina) –>
<link href=“/static/images/apple-touch-icon-152×152.png”
sizes=“152×152”
rel=“apple-touch-icon”>
<!– iOS 6 iPad (retina) –>
<link href=“/static/images/apple-touch-icon-144×144.png”
sizes=“144×144”
rel=“apple-touch-icon”>
<!– iOS 7 iPhone (retina) –>
<link href=“/static/images/apple-touch-icon-120×120.png”
sizes=“120×120”
rel=“apple-touch-icon”>
<!– iOS 6 iPhone (retina) –>
<link href=“/static/images/apple-touch-icon-114×114.png”
sizes=“114×114”
rel=“apple-touch-icon”>
<!– iOS 7 iPad –>
<link href=“/static/images/apple-touch-icon-76×76.png”
sizes=“76×76”
rel=“apple-touch-icon”>
<!– iOS 6 iPad –>
<link href=“/static/images/apple-touch-icon-72×72.png”
sizes=“72×72”
rel=“apple-touch-icon”>
<!– iOS 6 iPhone –>
<link href=“/static/images/apple-touch-icon-57×57.png”
sizes=“57×57”
rel=“apple-touch-icon”>
<!– Startup images –>
<!– iOS 6 & 7 iPad (retina, portrait) –>
<link href=“/static/images/apple-touch-startup-image-1536×2008.png”
media=“(device-width: 768px) and (device-height: 1024px)
and (orientation: portrait)
and (-webkit-device-pixel-ratio: 2)”
rel=“apple-touch-startup-image”>
<!– iOS 6 & 7 iPad (retina, landscape) –>
<link href=“/static/images/apple-touch-startup-image-1496×2048.png”
media=“(device-width: 768px) and (device-height: 1024px)
and (orientation: landscape)
and (-webkit-device-pixel-ratio: 2)”
rel=“apple-touch-startup-image”>
<!– iOS 6 iPad (portrait) –>
<link href=“/static/images/apple-touch-startup-image-768×1004.png”
media=“(device-width: 768px) and (device-height: 1024px)
and (orientation: portrait)
and (-webkit-device-pixel-ratio: 1)”
rel=“apple-touch-startup-image”>
<!– iOS 6 iPad (landscape) –>
<link href=“/static/images/apple-touch-startup-image-748×1024.png”
media=“(device-width: 768px) and (device-height: 1024px)
and (orientation: landscape)
and (-webkit-device-pixel-ratio: 1)”
rel=“apple-touch-startup-image”>
<!– iOS 6 & 7 iPhone 5 –>
<link href=“/static/images/apple-touch-startup-image-640×1096.png”
media=“(device-width: 320px) and (device-height: 568px)
and (-webkit-device-pixel-ratio: 2)”
rel=“apple-touch-startup-image”>
<!– iOS 6 & 7 iPhone (retina) –>
<link href=“/static/images/apple-touch-startup-image-640×920.png”
media=“(device-width: 320px) and (device-height: 480px)
and (-webkit-device-pixel-ratio: 2)”
rel=“apple-touch-startup-image”>
<!– iOS 6 iPhone –>
<link href=“/static/images/apple-touch-startup-image-320×460.png”
media=“(device-width: 320px) and (device-height: 480px)
and (-webkit-device-pixel-ratio: 1)”
rel=“apple-touch-startup-image”>

							

I’m loving the CLI executables right now, making loads of them! Remember you don’t get the memory or time out issues that you do on the web server php.

However I noticed that the regex broke when we had a hyphen separated option name, such as –most-recent for instance. It turns out PHP uses a command called getopt() (unsurprisingly). I was about to start using this when I realised that we can actually use Zend_Console_Getopt() instead!

Building on my previous post, I have changed the script somewhat. Check it out, it’s easy enough to follow!

 

#!/usr/bin/env php
<?php
/* Load Zend Framework or Freak out */
try
{
 require_once(__DIR__.'/../../inc/zend_init.php');
$config = array(
 'help' => ' Display this help',
 'most-recent' => ' Select most recent results',
 'year=i' => ' Select the Year year=[year]',
 'week=i' => ' Select the Week week=[week]',
 );

 $options = new Zend_Console_Getopt($config);
 $options->parse();
}
catch(Exception $e)
{
 die("\n".$e->getMessage());
}

if(!empty($options->year) && !empty($options->week))
{
 try
 {
 // code here
 }
 catch(Exception $e)
 {
 echo "\n** ERROR DETECTED **\n ".$e->getMessage()."\n\n";
 }
}
elseif(!empty($options->{'most-recent'}))
{
 //code here
}
else
{
 die($options->getUsageMessage());
}

Note the curly brackets! This is how you deal with hyphens when using Object notation. Also, in the config, you’ll see year=i. This means it is an integer. You can also have =s, being a string. Check the Zend Framework manual for more details, and have fun!