Archive for the ‘PHP’ Category.

How to create a jagged array in Objective-C

I don’t know if you ever ran into that kind of problem before, where you need to initialize a jagged array with Objective-C, but I did. I was disappointed to find out that Objective-C doesn’t have any easy way of recursively call a variadic method. I read several posts talking about using NSInvocation to achieve this, but as Apple stated, it’s not capable of doing so. Setting an argument on the NSInvocation object that is beyond the static arguments returned by the method signature will result in an out of bounds exception.

I found a way, it’s not super pretty, but it works just fine. Here’s a few examples of how simple this task is using other languages:

PHP:

<?php
    function createJaggedArray($length) {
        $args = func_get_args();
        array_shift($args); // We don't need the first parameter, it's already defined.
        
        $arr = array();
        while ($length--) {
            $arr[$length] = count($args) ? call_user_func_array('createJaggedArray', $args) : 0;
        }
        return $arr;
    }

    $jaggedArray = createJaggedArray(3, 3, 4, 4); // creates var[3][3][4][4]
    $jaggedArray2 = createJaggedArray(10, 3, 9); // creates var[10][3][9]

?>

ActionScript 3:

package {
    public class ArrayUtil {
        public static function createJaggedArray(len:int, ...args):Array {
            var arr:Array = new Array(len);
            
            while(len--) {
                arr[len] = args.length ? createJaggedArray.apply(null, args): 0;
            }

            return arr;
        }
    }
}

var myArray:Array = createJaggedArray(3, 3, 4, 4); // creates var[3][3][4][4]
var myArray2:Array = createJaggedArray(10, 3, 9); // creates var[10][3][9]

Here’s what I came up with for Objective-C. As you can tell, it’s quite convoluted. I’m sure there’s a better way of executing this, but at least, if you need something right away, that might answer *some* questions:

CreateJaggedLib.h:

@interface CreateJaggedArray : NSObject {
}

- (NSArray *)createJaggedArray:(NSNumber *)len, ...;
- (NSArray *)createJaggedArrayFromArray:(NSNumber *)len childrenLengths:(NSArray *)childrenLengths;

@end

CreateJaggedArray.m:

#import "CreateJaggedArray.h"

@implementation CreateJaggedArray

- (NSArray *)createJaggedArray:(NSNumber *)len, ... {
    NSMutableArray *argArray = [[NSMutableArray alloc] init];
    NSMutableArray *buildingArray = [[NSMutableArray alloc] init];

    NSNumber *eachArgument;
    if (len) {
        va_list argumentList;
        va_start(argumentList, len);
        while (eachArgument = va_arg(argumentList, NSNumber *) {
            [argArray addObject:eachArgument];
        }
        va_end(argumentList);
    }

    NSInteger length = [len intValue];

    while (length--) {
        NSMutableArray *nextArray = [[NSMutableArray alloc] init];
        for (NSInteger i = 1; i < [argArray count]; i++) {
            [nextArray addObject:[argArray objectAtIndex:i]];
        }
        
        NSNumber *value = [NSNumber numberWithInt:[[argArray objectAtIndex:0] intValue]];
        NSArray *resultArray = [self createJaggedArrayFromArray:value childrenLengths:nextArray];
        [buildingArray addObject:resultArray];
    }
    return buildingArray;
}

- (NSArray *)createJaggedArrayFromArray:(NSNumber *)len childrenLengths:(NSArray *)childrenLengths {
    NSInteger length = [len intValue];
    NSMutableArray *buildingArray = [[NSMutableArray alloc] init];

    while (length--) {
        if ([childrenLengths count] > 1) {
            NSMutableArray *nextArray = [[NSMutableArray alloc] initWithCapacity:([childrenLengths count] - 1)];
            for (NSInteger i = 1; i < [childrenLengths count]; i++) {
                [nextArray addObject:[childrenLengths objectAtIndex:i]];
            }
            NSNumber *value = [NSNumber numberWithInt:[[childrenLengths objectAtIndex:0] intValue];
            NSArray *resultArray = [self createJaggedArrayFromArray:value childrenLengths:nextArray];
            [buildingArray addObject:resultArray];
        }
        else {
            NSMutableArray *valueArray = [[NSMutableArray alloc] init];
            for (NSInteger i = 0; i < [[childrenLengths objectAtIndex:0] intValue]; i++) {
                [valueArray insertObject:[NSNumber numberWithInt:0] atIndex:i];
            }
            [buildingArray addObject:valueArray];
        }
    }
    return buildingArray;
}

@end

Call:

NSArray *jaggedArray = [<delegate> createJaggedArray:[NSNumber numberWithInt:3], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], [NSNumber numberWithInt:4], nil]; // Creates var[3][3][4][4]
NSArray *jaggedArray2 = [<delegate> createJaggedArray:[NSNumber numberWithInt:10], [NSNumber numberWithInt:3], [NSNumber numberWithInt:9], nil]; // Creates var[10][3][9]

As you can see, this can get pretty convoluted. I had to create a method that reacts differently for all the children parameters, since the recursive call of a variadic method isn’t supported with Objective-C. You could simply call the createJaggedArrayFromArray method using an array of lengths instead of using the nil-terminated list of arguments, but sometimes, it makes it easier for porting code from one language to another, to make sure it works the same way.

If someone has a better idea on how to fix this, please share! 🙂

New Website Launch!

After months and months of hard work, I’m proud to present our new website!

http://www.22squared.com

This site was made with Drupal 6. It uses A LOT of modules, as every other Drupal installations. The very cool thing is the search engine. We decided to implement Apache Solr to handle the site index for various reasons. One of them, is the powerful search engine and its auto-complete feature for the search form, but also for the related content.

The site only released the first phase of three. The second phase is in progress, which will add employee blogs and a blog aggregation engine. The site will be able to index all the blog contents and display related content throughout the site, as well as show existing content related to blog posts.

The third phase will include a public bookmarking engine, similar to del.icio.us. You will be able to share a set of pages, kinda like a portfolio of things you want people to see and share that via multiple social networking and/or directly through email.

Enjoy the site!

Zend Framework 2.0

Zend announced back in November of 2009 that the next major release of Zend Framework was on the way. They published the new framework’s roadmap and some of the new features. The upcoming release of Zend Framework has PHP 5.3 as a requirement, as it relies on namespace support. The main changes to Zend Framework is the MVC implementation, but there are many architectural and design changes as well. Here’s a summary of the new features.

The goal of Zend Framework is to improve the overall consistency, more consistent APIs relating to constructors, options and exceptions.

  • Unified constructor. All constructors will (optionally) accept an array for options or Zend_Config object as the first argument. This allows for more flexibility to add new arguments to the constructor, have a variable number of arguments and allow “named” arguments. Additionally, it’s a good technique for allowing Dependency Injection. As part of the initiative, most components will also have a “setOptions()” method to which the options array will be passed  (and which may be used later to reset object state). Typically, this will proxy to other setters. Many components in Zend Framework 1.x already do this: Zend_Application, Zend_Form, Zend_Validate, Zend_Layout, etc. We are simply extending this paradigm to cover all components. In order to reduce code duplication, we will likely introduce a zend\Options class, which will work roughly as follows:
    namespace zend;
    class Options
    {
        public static function setOptions($object, array $options)
        {
            if (!is_object($object)) {
                return;
            }
            foreach ($options as $key => $value) {
                $method = "set" . self::_normalizeKey($key);
                if (method_exists($object, $method)) {
                    $object->$method($value);
                }
            }
        }
    
        public static function setConstructorOptions($object, $options)
        {
            if ($options instanceof Zend_Config) {
                $options = $options->toArray();
            }
            if (is_array($options)) {
                self::setOptions($object, $options);
            }
        }
    
        protected static function _normalizeKey($key)
        {
            $option = str_replace('_', ' ', strtolower($key));
            $option = str_replace(' ', '', ucwords($option));
            return $option;
        }
    }
    
    use zend\Options as Options;
    class Foo
    {
        public $bar = '';
        public $baz = '';
    
        public function __construct($options = null)
        {
            Options::setConstructorOptions($this, $options);
        }
    
        public function setOptions(array $options)
        {
            Options::setOptions($this, $options);
        }
    
        public function setBar($value)
        {
            $this->var = $value;
        }
    
        public function setBaz($value)
        {
            $this->baz = $value;
        }
    }
    
    $foo = new Foo(array('bar' => 'baz'));
    echo $foo->bar; // "baz";
    
    $foo->setOptions(array('bar' => 'boo', 'baz' => 'bat'));
    echo $foo->bar . $foo->baz; // "boobat";
    
  • Options. In Zend Framework 1.x, the various components which accept options accept a variety of formats: some expect underscore_separated keys, other expect camelCasedKeys, others expect UPPERCASEDKEYS, and some expect lowercasedkeys. This leads to confusion for many, and also leads to difficulties debugging. The goal in Zend Framework 2.0 is to standardize option keys to correct this situation. Currently, they are leaning towards all_lowercase_underscode_keys. These are human-readable, contain only valid PHP variable characters, and make for a simplified option parsing implementation. Additionally, it is trivial to translate keys to camelCase (“str_replace(‘ ‘, ”, ucwords(str_replace(‘_’, ‘ ‘, $value)))”) for purposes of overloading – and this makes it easy to document option key => class property affiliations.
  • Exceptions. Each component will have an Exception marker interface, with exceptions defined for discrete exception types thrown by the component. The concrete exceptions will either extend the global Exception class or an SPL Exception, and also implement the component Exception interface. This allows to throw appropriate SPL exceptions while retaining a common Exception type (via the marker interface). As an example:
    namespace \Foo\Bar;
    interface Exception
    {
    }
    
    class InvalidArgumentException extends \InvalidArgumentException implements Exception
    {
    }
    
    try {
        throw new InvalidArgumentException();
    }
    catch (\Foo\Bar\Exception $e) {
    }
    
  • Design By Contract. They will be altering portions of the framework to follow the concept of design by contract, and new development will follow this paradigm. At first, this will take the form of refactoring to add interfaces/refactoring interfaces to reflect actual usage.
    Interfaces make creating alternate implementation of standard classes easier, while assuring that these implementations will continue to work with the classes that consume them. In many cases currently, they offer only abstract classes, with no equivalent interfaces; in other cases, the consuming classes use methods that are not part of the interface.
    In addition to this initiative, they will be eliminating some functionality intended to add flexibility to some of the standard classes. They have found that oftentimes this functionality leads to performance overhead as well as consumes maintenance time that could be used better elsewhere in the framework. As an example, the Dispatcher has a number of methods for adding custom class -> file mappings that are largely used and which use an unnecessary number of CPU cycles; refactoring this to follow only the standard use cases would ease maintenance, while having a good, simple interface would make creating alternate implementations for custom use cases easier.
  • Elimination of most singletons. Zend Framework has often been accused of “singletonitis”. While they’re not sure if they completely agree, in most cases, the singletons they have have presented a number of problems and led to difficult test cases. Additionally, in most cases, the singletons is unwarranted. They will be refactoring to eliminate these, including in Zend_Controller_Front. In exceptional cases, they will keep them; these include global operations such as autoloading and database connections.
  • Creation of components for general-purpose, cross-functional actions. A Number of components duplicate code, and they want to push the duplication areas into discrete components that the original components may then consume. Some of these include:
    • Plugins/Helpers/Strategies (seen currently in Zend_Controller_Front, Zend_Controller_Action_Helper, Zend_View (helpers and filters), Zend_Form (validators, filters and decorators), etc). Plugin discovery and loading could benefit from a common API.
    • Decorators (seen in Zend_Form; other areas could benefit from the pattern)
    • Factories (seen currently in Zend_Db, Zend_Navigation_Page, Zend_Auth, Zend_Translate, Zend_Cache, etc)
    • Caching (seen currently in Zend_Translate, Zend_Locale, Zend_Queue, Zend_Paginator, Zend_Feed_Reader, Zend_Db_Table, etc.)
  • Usage of new language features within plugin architectures. Currently, most plugins rely on the strategy pattern, but the mechanism differs between plugins. PHP 5.3 offers some compelling alternatives that they want to explore: __invoke() and closures. Closures are less compelling as we cannot do simple type-hinting on them. __invoke() offers perhaps the simplest solution, and could become a standard API for plugins.
  • Autoload-only. They will move to using autoloading throughout the framework. This solves a number of performance issues, as well as simplifies coding dependencies (particularily exceptions).
  • Namespaces. PHP namespaces benefit frameworks and libraries more than any other code bases, and Zend Framework can benefit from it greatly, particularily with components such as Zend_Search_Lucene and Zend_Controller. However, adopting namespaces does not come without a cost: all code will need to be rewritten to define and use namespaces. This will be the single biggest BC break they introduce.
    They also plan to introduce a separate namespace for unit testing, and are currently looking at either \test\zend, \zend\test, or \testzend. This, along with per-component namespaces, will help prevent naming collisions within the test suite.
  • goto. Goto is often considered “evil”, but is invaluable when creating Finite State Machines (FSM) and parsers; usage of goto will be evaluated on a case-by-case basis. Some examples of components that could potentially benefit from such an implementation include Zend_Search_Lucene (which already implements a FSM), the MVC (more below), Zend_Ical, and Zend_Markup (though not all of these may make use of it).
  • Specifics on Plugin architecture changes

For the MVC changes, there is a great article on Pádraic Brady’s Blog.

You can also find all the information about this new version of Zend Framework on Zend’s website at http://framework.zend.com/wiki/display/ZFDEV2/Zend+Framework+2.0+Roadmap.

PHP Error Handler

Hey, I thought about sharing this little piece of code. Back a couple years, I was heavily involved with PHP projects. I came up with the idea of writing an error handler class system that would allow me to add custom errors and return Boolean values from class methods and functions. It also had a method to list errors in a cleaner way than PHP’s default error handler. Here’s the concept behind it.

The way I designed this system is using a Singleton pattern to accumulate errors. By using a static variable, PHP stores this object in memory and can be referred to at a later time. Of course, there’s no real instance creation prevention in PHP, so we’ll skip the part of declaring a private constructor.

class Error {
    private $errorList;
    private $errorCount;

    public function getInstance() {
        static $errobj;
        if (!is_object($errobj) || !is_a($errobj, 'Error')) {
            $errobj = new Error();
        }
        return $errobj;
    }

    public function raise($errCode, $errString, $errType = "general") {
        $errobj = self::getInstance();
        $errobj->errorList[$errType][(int)$errobj->errorCount]['code'] = $errCode;
        $errobj->errorList[$errType][(int)$errobj->errorCount]['message'] = $errString;
        $errobj->errorCount++;
    }

    public function errorOccured() {
        $errobj = self::getInstance();
        if ($errobj->errorCount > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    public function getList() {
        $errobj = self::getInstance();
        return $errobj->errorList;
    }
}

Now that we have the base of our error handler class, we can create new classes that extend that master class. Here’s an example:

class ErrorDB extends Error {
    public function raise($db_exception, $message) {
        parent::raise(E_USER_WARNING, $message . "\r\n" . $db_exception->getMessage(), "database");
    }
}

This class will use the parent’s “raise” method to add the error to the error stack. Note that the last argument, “database” is the category in which this error will appear under. Here’s an example of how to use this class. Let’s assume that you already have a PDO database object.

<?php

    try {
        // Database operation here
    }
    catch (PDOException $e) {
        ErrorDB::raise($e, "Cannot perform database operation 'xyz'");
    }

?>

Next, I’ll show you how to handle PHP’s native errors with the same system.

class ErrorPHP extends Error {
    public function raise($errno, $errstr, $errfile, $errline) {
        // We don't really care about E_STRICT errors
        if ($errno != E_STRICT) {
            parent::raise($errno, $errstr . " (in " . $errfile . ", at line " . $errline . ")", "PHP Errors");
        }
    }
}

set_error_handler("phperror");

function phperror($errno, $errstr, $errfile, $errline) {
    ErrorPHP::raise($errno, $errstr, $errfile, $errline);
}

Once the page is done loading, you can call the getList() statically from Error, like $errors = Error::getList();, to return a multi-dimensional array containing all the errors that occured. You’re free to display it anyway you’d like.

I hope you find this article useful!
Thanks for reading.

AMF Tutorial part 3 added

Hey! I finally took the time to write up the last part of my AMF tutorial.

Hope it answers your questions!

-Simon

Read More

AMF Tutorial part 2 added

I know, I was supposed to write to my blog more often than this, but I was pretty busy. Anyway, here it is! You can access it through the Tutorial link at the top of the page!

Enjoy!

PS: Feel free to leave any feedback.

Read more

New Tutorials Section!

Hello all, I just now added a new section to my blog, a tutorial section.

For now, there is only a partial one on AMF connectivity between ActionScript and PHP.

Read more