UISpringBoardButton to get started


For a while now, Apple has been delighted in defining the de facto standard for the look of most of the applications in the App store. Which takes me to my next point, when we create a UIButton, we get a look that is pretty much the same always, except when we specify a background image, but then again, we need to comply with several UI rules to be able to use all the buttons and images quite nicely.

There is one type of button that I always liked the way they look, and those are the welcome screen buttons or the SpringBoard. In one of my current projects, I had to mimic how these icons look, needless to say, I went down into Stack Overflow looking for ideas and I did found some nice ideas.

So, the main task was to create some sort of UIButton with a UILabel below placing some sort of caption and showing and also reproducing the shiny icon on the button. To accomplish this, we first need to subclass the UIButton class, which brings us all the basic interactions with a button. So, basically, we'd had something like this:

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "ImageHelpers.h"

@interface UISpringBoardButton : UIButton

//Name of the icon to load from the project
@property (nonatomic, retain) NSString * IconName;

//Title of the button
@property (nonatomic, retain) NSString * ButtonTitle;

//This is where the magic happens
- (id)initWithFrame:(CGRect)frame andIcon:(NSString*) iconName andText:(NSString*) ButtonText;
- (void)initButtonWithSize : (CGSize) buttonSize;
- (void) createButtonWithFrame: (CGRect) buttonFrame;


First, we have 2 properties that will retain the name of the Icon that will represent our button and the Title of the button, which will be displayed in the UILabel below it. For now, I will just focus on getting the job done, and for those of you enjoying "copy + paste" the code was made using XCode 4.2 in the ARC age, so you should remember that. If you are as newb as I was a few weeks ago and didn't knew what the heck ARC was, then consider checking out this. Having said all that, Let's go into the code! First, you should make yourself an extender method for resizing images, I made a class like this one:


//Sorry about the name, old C# habbits...
@interface UIImage (ImageHelpers)

- (UIImage *)getIconOfSize:(CGSize)size withOverlay:(UIImage *)overlayImage;
- (CGContextRef)createBitmapContextOfSize:(CGSize)size;
- (UIImage *)scaleImage:(UIImage *)image toResolution:(int)resolution;


With the exception of the first method, the other two I took them from Fulvio's implementation in his answer this question. Thanks for that Fulvio! Without further ado, this is how the first method would be now:

- (UIImage *)getIconOfSize:(CGSize)size withOverlay:(UIImage *)overlayImage 
    UIImage *icon = [self scaleImage:self toResolution:size.width];
    CGRect iconBoundingBox = CGRectMake (0, 0, size.width, size.height);
    CGRect overlayBoundingBox = CGRectMake (0, 0, size.width, size.height);
    CGContextRef myBitmapContext = [self createBitmapContextOfSize:size];
    CGContextSetRGBFillColor (myBitmapContext, 1, 1, 1, 1);
    CGContextFillRect (myBitmapContext, iconBoundingBox);
    CGContextDrawImage(myBitmapContext, iconBoundingBox, icon.CGImage);
    if ( overlayImage != nil )
        CGContextDrawImage(myBitmapContext, overlayBoundingBox, overlayImage.CGImage);
    UIImage *result = [UIImage imageWithCGImage: CGBitmapContextCreateImage (myBitmapContext)];
    CGContextRelease (myBitmapContext);
    return result;

Now that we have our helper (refered in the #import "ImageHelpers.h" line as well) we can code the button at ease. First, we need to synthetize our properties, coming from a Visual Studio background, I'm still wondering why XCode can't do this for me, but I'm hopeful to see some nice products soon. Sigh... anyways, here it goes:

@implementation UISpringBoardIcon

@synthesize IconName;
@synthesize ButtonTitle;

Good stuff starts now, we need to write a new init method much like the initWithFrame, but with some extra stuff and then we call to the guy that is going to take care of assembling the control:

- (id)initWithFrame:(CGRect)frame andIcon:(NSString*) iconName andText:(NSString*) ButtonText
    self = [super initWithFrame:frame];
    if (self) 
        self.IconName = iconName;
        self.ButtonTitle = ButtonText;
        [self createButtonWithFrame: frame];
    return self;

Once we build the button we call the createButtonWithFrame method that handles creating the UILabel, placing it in the according place, aligning the text in the center and placing the lineBreakMode so that the system handles breaking the text accordingly if is too big.

- (void) createButtonWithFrame: (CGRect) buttonFrame
    CGSize sz = [ButtonTitle sizeWithFont: [UIFont systemFontOfSize: 10]];
    float width = self.frame.size.width;
    float y = self.frame.size.height - sz.height;
    //Need to add some space between the button and the UILabel
    CGRect labelFrame = CGRectMake(0, y + 5, width, sz.height);
    UILabel * textLabel = [[UILabel alloc] initWithFrame: labelFrame];
    textLabel.text = ButtonTitle;
    textLabel.font = [UIFont systemFontOfSize:10];
    textLabel.textAlignment = UITextAlignmentCenter;
    textLabel.lineBreakMode = UILineBreakModeMiddleTruncation;
    [self addSubview:textLabel];
    CGSize buttonSize = CGSizeMake(buttonFrame.size.width, buttonFrame.size.height - sz.height - 5);
    [self initButtonWithSize: buttonSize];

Now, all we need is to create the button using the overlay provided by rpetrich on his answer to the same question stated above. Actually, using Fulvio's code this is a pretty simple process:

- (void)initButtonWithSize : (CGSize) buttonSize
    UIImage *overlayImage = [UIImage imageNamed:@"AppIconOverlay.png"];
    UIImage *image = [UIImage imageNamed: IconName];
    UIImage *profileImage = [image getIconOfSize:CGSizeMake(50, 50) withOverlay:overlayImage];
    self.imageView.layer.masksToBounds = YES;
    self.imageView.layer.cornerRadius = 10.0;
    self.imageView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.imageView.layer.borderWidth = 1.0;
    [self setImage: profileImage forState: UIControlStateNormal];

This is it! Creating a new one is very easy, just one line of code:

  UISpringBoardIcon * button = [[UISpringBoardIcon alloc] 
                                      initWithFrame: frame 
                                            andIcon: @"tux-icon.png"
                                            andText: @"Going home"];

The result should look like this:

Hope this can help! As usual, comenting is not forbidden.

Edit The source code can be downloaded here from my dropbox.

Hello iOS!!!

I've been playing with the idea of doing some mobile development for some time now, but never had the time to do it. Guess what?? I'm really digging into iOS now! For the time being with a borrowed Macbook (they're so expensive!!) but I should get my Mac Mini by the end of this year (Santa has been good to me!). Does this mean that I'm done with PHP or C#? Nope, but I should be really busy with iOS for a while now. Hope I can write something cool soon!!!

Automatically building FluentNHibernate mappings


As those who suffered data access and passed to the ORM world know, one of the key benefits of using a ORM like nHibernate is productivity, having an object oriented way to manage object persistence. However, not everything is just roses and candles, and nHibernate has mappings. Those tedious xml files we used to write to map a class into an object representation were a real pain in the a**.

However, then we had Fluent nHibernate to save our days and everything went better, we had fluent mappings, which rock much more than the old way of making mappings. For those of you who haven't heard of Fluent nHibernate (FNH from now on) it's a wonderful tool that allows you (amoong other really useful things) to map your data classes to nHibernate and allow you to do stuff like Lazy Loading and many other perks. It supports a great deal of the functions provided by nHibernate but writing pretty classes and not nasty xml. Ok, no more chatty stuff... Let's see a simple example, say you have this class:

public class Product
 public virtual int Id {get; set;}
 public virtual string Name {get; set;}
 public virtual float BasePrice {get; set;}
 public virtual Category Category {get; set;}

This class can be mapped to nHibernate using something called ClassMap provided by the most useful FNH, like this:

public class ProductMapping : ClassMap<Product>
 public ProductMapping()
  Id( x => x.Id );
  Map( x => x.Name );
  Map( x => x.BasePrice );
  References( x => x.Category );

Ok, this is pretty much it... if you want to read more on Fluent Mappings, be sure to check their wiki which is a pretty good introduction and if you are new to nHibernate I'd have to recommend Jason Dentler's nHibernate 3.0 Cookbook (I know I'm missing a link here...), which is also pretty good.

Now, to the purpouse of the post, in my interest on speeding my development, I started applying those stuff that I learned from Steven Sanderson's about Scaffolding in an awsome serie of blog posts he made.

So, instructions... First thing you need to do is install the MvcScaffolding package. Then you should create your own Scaffolder project. The steps are pretty much like this:

 Install-Package MvcScaffolding
 Scaffold CustomScaffolder AutoFluentMapper

Now you will get a Powershell file and a T4 file. For your Powershell write this:

[T4Scaffolding.Scaffolder(Description = "AutoFluentMapper. Scaffolding mappings")][CmdletBinding()]
    [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
    [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
 [switch]$Force = $false

$namespace = (Get-Project $Project).Properties.Item("DefaultNamespace").Value;
$folder = Get-ProjectFolder $DomainFolder;

$entitiesNamespace = $namespace + "." + $DomainFolder;
$mappingsNamespace = $namespace + "." + "Mappings";

if (!$BaseEntity)
    $BaseEntity = "System.Object";

foreach ( $folderItem in $folder )
    $entityName = $folderItem.Name.Replace(".cs", "");
    $entityFullName = $entitiesNamespace + "." + $entityName;
    $entity = Get-ProjectType $entityFullName -Project $Project;
    if ( !$entity ) { Write-Host "Entity $entityFullName not found!"; return; }
    $mappingName = $entityName + "Mapping";
    Add-ProjectItemViaTemplate -OutputPath "Mappings\$entityName" `
                           -Template "AutoFluentMapperTemplate" `
                           -TemplateFolders $TemplateFolders `
                           -SuccessMessage "Added Mappings output at {0}" `
                           -Model @{ 
                                    ModelType = $entity; EntityName = $entityName;
                                    Namespace = $mappingsNamespace; EntityNamespace = $entitiesNamespace;
                                    BaseEntity = $BaseEntity
                            -Project $Project -CodeLanguage $CodeLanguage -Force:$Force

Ok, I know you don't toss an amount of code like this without a good explanation, so I'll try to explain myself. The first block defines the list of parameters that our Scaffolder will accept, if you take the powershell script that you get when creating a new scaffolder, we only added a DomainFolder, which we will use to search in that folder the domain entities and a BaseEntity to check if we have a normal class or if we have model inheritance. Then, we have a small block of code to manage the names of the namespaces for the mappings, and finally if no base entity name is provided, we'll assume that our base model is System.Object.

After we've done all these small twitches, all we need is to process each file we find in the folder specified by DomainFolder. We get the name of the entity, then the full name considering the namespace, and finally we add the new file, pretty much like this:

$entityName = $folderItem.Name.Replace(".cs", "");
$entityFullName = $entitiesNamespace + "." + $entityName;
$entity = Get-ProjectType $entityFullName -Project $Project;
if ( !$entity ) { Write-Host "Entity $entityFullName not found!"; return; }

Add-ProjectItemViaTemplate -OutputPath "Mappings\$entityName" `
 -Template "AutoFluentMapperTemplate" `
 -TemplateFolders $TemplateFolders `
 -SuccessMessage "Added Mappings output at {0}" `
 -Model @{ 
  ModelType = $entity; EntityName = $entityName;
  Namespace = $mappingsNamespace; EntityNamespace = $entitiesNamespace;
  BaseEntity = $BaseEntity
 -Project $Project -CodeLanguage $CodeLanguage -Force:$Force

Ok, now we need to work our T4 template. If you don't know what T4's are all about, then consider checking out Oleg Sych's post on T4 templates which is the way to start and according to Scott Hanselman is a place with some good resources. Now, what will we do with our T4, we will generate our mapping by inspecting into the code's properties.

This is the part were I'll have to apologize, because when I generate my models I include an Id property, which is an int, so I didn't inspected for that property and just added hard coding it, feel free to make changes and do tell me of new ideas...

The T4 template I built is based on one idea, take a model, check if it inherits from something other than the base model, inspect the properties and build the mappings accordingly:

var modelType = (CodeClass)Model.ModelType;
var baseEntityName = (string)Model.BaseEntity;
var parentEntities = (CodeElements)modelType.Bases;

var derivedFromBase = false;

foreach( CodeElement parentEntity in parentEntities ){
 if ( parentEntity.Name.Contains(baseEntityName))
  derivedFromBase = true;

var inheritable = derivedFromBase ? "ClassMap" : "SubclassMap";

var properties = new List<CodeProperty>();
var enumerables = new List<CodeProperty>();
var references = new List<CodeProperty>();

So, the idea was to separate the properties (or attributes of the domain entities) in 3 groups:

  • Properties: Those attributes that have a basic type, say strings, integers, DateTimes, and stuff like that.
  • Enumerables: Those attributes that define an IEnumerable collection, most commonly seen on many to one or many to many (not supported yet, sorry...) relationships
  • References: Thos attributes that reference another attribute of our domain

Having these ideas in mind, and will a little of T4 and EnvDTE magic we can get a fully fledged template for our Scaffolding needs. All we need now is to run it, much like this:

Scaffold AutoFluentMapper Entities -BaseEntity BaseDomainEntity

For those interested only in the how it works idea, the Entities argument defines the name of the folder where I have my entities, and their namespace is infered from there (convention over configuration..). The -BaseEntity parameter is used to determine the base of your domain models to check for class inheritance in nHibernate models, if you ommit this argument, I'll assume it's System.Object. Besides these 2 arguments, this is just a regular plugin and I've tried it already. Hope you enjoy it!

If you are using this code as part of your projects, send me an email or leave a comment to know that I've actually helped somebody, which is the main thing that encourages me to write more of this stuff. The Source code can be downloaded here as a zip file.

SOLID PHP : Laying Foundations for applications (Part 1)


This will be the first of (hopefully) a few articles explaining (with code and all the neat stuff) some basics on software design for those daring to do this job. PHP has been a language long cursed by many programmers, some say the problem is that is not a compiled language, others say that has weak typing, some talk about performance and there are many many talks about it, you even get to see people that say it sucks! and they just can't stop wondering why the some big guys use PHP. Personally, I don't believe in bad languages (with some exceptions, cough.. vb.. cough) but I rather think in bad programmers or to be less agressive in programmers who dislike different ways to do things (now that I think about it, I don't know which one is worst...)

Anyways, I've chosen to do my examples using PHP because there is plenty of literature about the subject using C#, Java or even C++. When we talk about SOLID, the first thing we need to say is that SOLID is a list of 5 principles that encourage several good practices, they're good, they're pretty simple, however, they are not the only ones. There are many principles on software design, specially because software design is for one a young science and therefore there is many new stuff to find, and secondly because there are (obviously) more than 5 design principles to do good software, however these 5 are quite important and basic. Now, will these design principles make my code perfect? Well... nope, no way!! there is no such thing as perfect code (hello worlds not included) and mostly because when we write code, we will make mistakes (remember, we are humans...), however, following these principles will prevent a lot of these mistakes, will make your code more readable and will make your system (among other things) scalable.

Today I will start talking about the first principle, which is the Single Responsability Principle. This principle states one elementary truth and its that there should be one (and only one!) reason for a class to change, sadly I can't make the one bolder than the rest of the principle, but I hope the parenthesis give the correct amount of dramatism. Now, when we say "reason for a class to change", what's that? With reason to change we mean reasons that will make you touch (edit) the code again, and using that definition we have to agree that touching (editing) working code has a problem : it introduces bugs...

Now, let's stop being so chatty and see some code shall we?

  class UserManagement
   public function LogUserIn($userName, $password)
    $host = $dbConf["host"];
    $dbUsr = $dbConf["user"];
    $dbPwd = $dbConf["pass"];
    $link = mysql_connect($host, $dbUsr, $dbPwd);
    $logger = new FileLogger();
    if ( !$link ) {
     $logger->Log("Error opening connection to DB");
     return false;
    if ( !mysql_select_db($dbConf["db"], $link)){
     $logger->Log("Error selecting DB");
     return false;
    //Prevent some injection over here...
    $user = mysql_escape_string($userName);
    $pwd = mysql_escape_string($password);
    $query = "SELECT COUNT(*) FROM Users " .
       "WHERE user = '$user' AND Pass = '$pwd'";
    $rsc   = mysql_query($query, $link);
    if ( !$rsc ) {
     $logger->Log("Error querying DB");
     return false;
    $row = mysql_fetch_array($rsc);
    return count($row) > 0 && $row[0] > 0;

Some may say, OK, it's a perfectly working function, what's the fuzz all about? Well, what this function does? The function itself does many things:

  • Connects to the database
  • Builds the Log system explicitly and logs errors
  • Handles domain logic code (the whole COUNT to figure out if the user exists..)

So, this function has several reasons to make it change. What happens if we want to change the database? We need to change this code. What happends if we change the Log system? We need to change this code. What happens if we also have to check some more stuff? We also have to touch this code. So, the code has many problems that may make it change. How do we solve this? Using Contracts(a.k.a Interfaces). If we are to connect to the database, we define how the connector has to be, if we are going to perform logging, we define how the Logger has to be and so on. If we do all that, then our class can manage only one thing, say managing the Login of a user. Imagine now we have these two interfaces:

 interface IDatabaseConnection
  public function OpenConnection();
  public function BuildQuery($queryString);
  public function EscapeString($string);
  public function CloseConnection();
 interface IDatabaseQuery
  public function GetAsRowCollection();
  public function GetScalarValue();
  //many more...
 interface ILogger
  public function Log($message);

With these interfaces, we define contracts. For instance, we're saying that we want that any class implementing the ILogger interface needs to have a Log function receiving a message argument. Interfaces can even force types using type hinting and therefore providing even better defined contracts, which is always cool.

Once we have defined the contracts we need, then we could rewrite our code to something like this:

 class UserManagement
  private $logger;
  private $dbConnector;
  public function __construct(IDatabaseConnection $connector, 
         ILogger $logger){
   $this->logger = $logger;
   $this->dbConnector = $connector;
  public function LogUserIn($userName, $password)
   //Prevent some injection over here...
   $user = $this->dbConnector->EscapeString($userName);
   $pwd = $this->dbConnector->EscapeString($password);
   $query = "SELECT COUNT(*) FROM Users " .
      "WHERE user = '$user' AND Pass = '$pwd'";
   $command   = $this->dbConnector->BuildQuery($query);
   if ( $command != null ) {
    $this->logger->Log("Error building DB command");
    return false;
   $count = $command->GetScalarValue();
   return $count != 0;

We've written code far more readable, with no dependency in anything but domain logic, well, perhaps we're building SQL code in here, and that's not good, but to prevent having to do that, we could use Propel or Doctrine and instead of writing plain and cold SQL we could use an ORM framework to do the dirty work for us. I'm just putting a simple example here using traditional database connection, but if you have an elaborate application, then consider seriously using Propel or Doctrine.

Now we would need to implement the ILogger interface and the IDatabaseConnection interface to be able to perform the operations we need, however, if we need to change the way we connect to the database, then we'll change the implementation (or add a new one!) of our IDatabaseConnection and that's just about it!

However, do keep in mind that the issue with the Single Responsability Principle is that it will help you with dependencies, but it will make your design grow substantially. We started with a class and ended with 3 interfaces and also their implementations (3 more classes) and finally the same (but reduced) class. Bottom line is : these principles are to design a propper application, but if you're making your own small tool, like some scrapper or a small reader for rss news, SOLID principles are not the thing you should be considering, they apply when you are facing an application that may grow.

Codeplex vs "The World"


A few minutes ago, I had the astounding oportunity to read a really lovely blog post made by the CodePlex team, in regards to the preferences of developers when building open source projects.

Basically, the post narrows down to this image:

Very suggestive, specially in the Windows part, where you are lead to believe that a 38% of the users building open source projects, who like Windows most, preffer CodePlex. Now, let's see the facts, according to the post they've had "... over 1,000 responses to the latest survey ..."

Now, let's do some basic math..., let's suppose that the CodePlex folks polled 2000 people (I hardly think so, but let's think it anyways). And let's think that we had 10 Linux project builders and 10 Mac projects builders. So, that would give us 1980 Windows project builders (I,m there!! wait... I didn't made the poll, so I'm not there :( ). From those 1980 Windows project builders, we have a 39% (also rounding in favour because I just love these folks), which is 772 project builders!. Now Github has 2,448,911 repositories and 888,893 users (checked right now), so the amount of Windows users following the data collected in the poll, should be around 328890 users (give or take). On the other hand, Codeplex has around 24005 projects (seems that they're not as proud as Github of their statistics, so I had to browse the directory) and an undisclosed amount of people.

The number speaks for themselves, without a deeper comprehension of the real amount of projects being held on either Github or Codeplex it's all a matter of "whatever floats your boat...". One thing to consider, I completely ignored the Linux and Mac community, but do keep in mind some hard facts:

  • Open source started on Linux, so most Open Source project builders are Linux based
    • Linux devs, by definition, (mostly) hate Windows
  • A big percent of PHP project developers are Linux based (there are plenty of PHP projects)
  • Almost all iPod/iPhone/iPad developers are Mac based, and also (mostly) hate Windows

My personal oppinion is that I hardly believe that over 1000 responses in a poll gives a fair amount of usage on open Source projects. However, measuring the total amount of projects on might give a better insight of who's more popular, being Github the one with more preference, with 2,448,911 repositories!

As for the "...Mercurial preference dropping sharply...", I do not believe that Mercurial is going to be leaving the market anytime soon, quite the opposite, there is a vibrant comunity, at Google Code specially, and Mercurial does offer plenty of strengths. So my opinion of the post is biased, sorry about that guys, but I'm not convinced...

Well, this is it, remember this it's my personal oppinion and it's by no means the correct one, but do think about what I've written

Source codes available on Github


Finally I've managed to setup my Github account and I can put my examples there, let's hope that now I can start documenting other projects to be able to share them.

If you find any project on my Github account and I haven't been able to create the related blog post, or the project documentation is null, feel free to contact me and I'll try to reply ASAP. Thanks to all the folks commenting and reading the blog!

PHP LINQ: A nice alternative


A few days ago, I was browsing through the CodePlex projects, to see if I could find something nice to try, and it happens I did. I’ve always been a defender of .NET and it was the motive of several discussions with my (not so fan of .NET) friends. One feature that I’ve always enjoyed on C# was the introduction of LINQ on .Net 3.5 which I believe is one of those life changers of the language.

For those of you who hate .NET or just don’t care about it, LINQ is a powerful way to access/query your data through a set of extension methods created on the IEnumerable interface. For those of you who’ve never heard of it, you can do amazing things like this:

var aCollection = new List<AnySortOfClass>();

var query = from item in aCollection 
   where item.APropertyName == “Nice!!” 
   select item;

foreach (var item in query )
 Console.WriteLine(“Found an item: ” + item.Name);

This is a pretty neat stuff to have when programming, at least you can kiss goodbye to all the nasty for loops (or foreach loops) looping into an array just to filter data. The idea of taking the SQL approach into other programming languages, at least for performing data related tasks is very reasonable one, so I believed that LINQ would be conceived for at least a few other languages.

Due to the fact of LINQ heavy use of anonymous types and lambdas (supported on PHP until 5.3, at least directly, before we could use create_function() ), I didn’t had much hope for a PHP version of LINQ to show up, then I found PHP LINQ, a project hosted in CodePlex and maintained by Martin Balliauw.

After browsing for a couple minutes the source code and the examples, I have to say, that PHP LINQ does have some potential. For instance, there is a Zend_Db_Table adapter for those who use Zend framework, which is kinda neat. You can do something like this:

Assuming you have a EmployeeTable (employee.php)

class EmployeeTable extends Zend_Db_Table {
    // table name
 protected $_name = 'employees'; 
    protected $_primary = 'Id';

You can now perform this query:

$employeeTable = new EmployeeTable(array('db' => $db));

$result = from('$employee')
 ->in( $employeeTable )
 ->where('$employee => strlen($employee->Name) < 5')
foreach ($result as $employee){
 // do something with $employee...

I think this is a rather nice way to work around queries for the database. Anyways, will try to do on my free time (which is kinda scarce these days) a driver for using with Propel, which is the ORM I like using!

Installing Smarty


A Quick & Dirty version...

Smarty is one of the most important template engines in the PHP development world. It provides a rather easy and "clean" usage and setting it up is not hard, dispite of some quick-install and Windows tutorials I saw in my early documentation seeking moments.

Before anything, I'll assume that you are not looking for a tutorial on Smarty, this will cover only how to get it running. Well, here is a simple list of how to set Smarty up in your development environment.

  1. Download Smarty It's free, lightweight and fast. Also, it's the only(?) real template engine available for PHP.
  2. To be able to configure Smarty, you'll have to add the downloaded Smarty project to your web project (I assume you have it in a folder), and load it, nothing fancy!

    Take for instance, the case where I have Smarty in my server in lib\smarty. If I use this line in my entry point file(usually, my index.php file):

       define("PATH_BASE", dirname(__FILE__));
       define("DS", DIRECTORY_SEPARATOR);

    Then, I'll be able to load Smarty with a really simple call:

       require_once( PATH_BASE . DS . "lib" . DS . "smarty" . DS . "Smarty.class.php" );
       $smartyObject = new Smarty();

    On a side note, I received a comment some time ago about the DIRECTORY_SEPARATOR constant definition not working. I've looked upon the problem and it seems that the constant is part of the PHP core for Directories.

  3. Now that Smarty has been set up, we need to point out the directories where to look for and store generated files. This can be achieved with 3 simple instructions:

    I assume that PATH_TEMPLATES is the path to your templates folder. That's it! With a few lines of code, you have Smarty up and running! All you have to do now is just assign variables and load the template. Like this:

       $smartyObject->assign("message", "Hello world!");

Uploading code

Currenlty setting GitHub for storing code. Blogger still sucks on storing code. That's why I haven't posted an online version of the Propel+CodeIgniter integration. If anyone knows a better way, do Comment!

Applying design patterns to web development


Part 1: The strategy pattern

One of my biggest efforts as a developer is to apply design patterns to my software designs and implementations. When I’m working with PHP is where I most feel the lack of OO approaches in many cases. PHP started as a procedural language, with a few functions serving for a limited amount of tasks, but like anything in this world, it has evolved into a more mature language. The problem is that many tutorials around the web are meant for starting as a developer and tend to leave Object Orientation out of the box, which is a trend that I find awful.

Sadly, there are still many PHP developers writing procedural code and calling it object oriented because they use the word class. Writing OO code is a bit more complex than that, we need to “think” how to express our problem into objects and how to make them communicate, not to create monolithic systems with strongly coupled components, which turns into software impossible to maintain, document, test and most importantly reuse and scale.

Well, back to the main idea, in this blog post I intend to use the strategy design pattern, which is one of the most implemented design patterns when it comes to web systems. The definition of the strategy pattern is:

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

The classic scenario is a situation where we can employ different variants depending on the environment. For instance, Session Management is an important task on every web application. If we are going to create a small application, then using the standard PHP session implementation, we are good to go. But this does pose two main problems:

  1. If we are in a shared hosting, anybody in the same server can work around the server´s security and copy the session files thus gaining access to data we don’t want them to have.
  2. If we want to scale our application, like adding extra servers, moving the application to a cluster or something like it, sharing the session files is a nightmare for managing the sessions

So, we have two main scenarios, where we are able to use the standard session driver and where we have to use a more advanced session management system, like for instance a database approach or integrating with Memcached or another powerful solution.

The initial approach is to write a PHP file called sessions.php and there do something like this:

$driver = $configuration[“session”]->getFile();
include $driver . “.php”;

And driver would be a file performing the calls to the session_set_save_handler function which changes the functions for managing the sessions, and of course, the implementation of such functions.

An approach like that one does the job, but we would have no objects, just a bunch of files. The real Object oriented version would be defining the contract of how we want to interact with the drivers. In our case, we have a session driver, which could hold a few operations, basing on the session_set_save_handler function arguments, we would need 6 methods in our interface: Open, Close, Read, Write, Destroy and GarbageCollect.We would have something like this:

interface ISessionDriver
   public function Open();
   public function Close();
   public function Read();
   public function Write();
   public function Destroy();
   public  function GarbageCollect();

Now, we have an interface, and we can register the interface as the session provider. To do that we have again two methods, the first one is loading from the configuration the class we want to load, and we’ll see the second soon on how to use Dependency Injection.

The idea is very much like the first functional approach, include the template file, but now we know that we’ll have a class implementing the ISessionDriver interface, a class which respects a contract previously established by me. Again, we would do a code quite similar, but now we would check:

$driver = $configuration[“session”]->getFile();
   include $driver . “.php”;
   $driverInstance = new $driver();

   if ($driverInstance instanceof ISessionDriver){
      //register the session driver
      throw new SystemException(“Expecting an ISessionDriver here!”);

With that we finish the first part of how to decouple our classes into a more reusable environment, applying the strategy design pattern and we will get deeper into it soon by using dependency injection to make this design even more decoupled.

Source code is highlighted!

Thanks to Alex Gorbatchev's Syntax Highligther and a really smooth guide found here now the posts have full source code coloring!

I should be migrating older posts soon..

The whole blog is migrated to Gorbatchev's syntax highlither!

Using Propel with CodeIgniter


CodeIgniter is a nice development framework used for PHP applications. Is light, small, compact and it does provide an “Object Oriented” solution for web development. However, it lacks a major component, which is a database infrastructure. CodeIgniter’s models provide a rather quick and dirty solution for database access, which is nice for small projects, because we cannot be thinking on the large solution every time we write a piece of code, but for most decent application, a small approach like that one, just won’t do it.

The solution? Well, using an ORM framework. I’m a defender of ORM mapping solutions and I believe that they are here to stay, just like the Korn song. Anyways, there is no easy way to integrate CodeIgniter with Propel; they just don’t seem to get along. I’ve read a wiki post explaining how to do it, but I found it quite disturbing for a few reasons

  • A solution shouldn't tell you to change the apache configuration
  • Propel has a really powerful autoloading system, why did they not prepared for using it?

Anyways, the idea I came up with is to integrate Propel as an independent library for the framework using the libraries autoloader, which is much like the post I'm talking about, but I made a few tweaks. CodeIgniter stores it’s plugins into the folder system/libraries, so the best way to start is copying Propel’s runtime into that folder. Create a folder called propel and copy the runtime files (propel/runtime/lib/*) there.

After copying Propel we can create the library’s entry point, which is a file called propel.php and there we will write a class to load Propel:

class CI_Propel
  public function CI_Propel()
     require dirname(__FILE__) . DS . "propel" . DS . "Propel.php";
     Propel::init(BASEPATH . "application/config/propel-conf.php");

In this class we require the Propel main file (Propel.php) and we tell it where he can find the configuration file. The configuration file is the xml file generated by Propel storing the database configuration and we must specify it in order to get propel running.

Now we’ve created our driver, we need to tell CodeIgniter to load our library, and this is done by going into the application/config/autoload.php file, where CI stores the libraries to be loaded with the application. We need to look for the line:

$autoload['libraries'] = array();

And change it with the information we need to load propel:

$autoload['libraries'] = array('Propel');

Now, we need to copy Propel’s models into the models folder located in the application folder and the configuration files generated should be on the application/config folder. Now the mapping configuration files should be edited to load the models properly; Propel works with relative routes to the models and it breaks when we try to load those models from a different path. You should look for lines like this one:

'CategoriesTableMap' => 'Northwind/map/CategoriesTableMap.php'

And change them for the real CI path:

'CategoriesTableMap' => BASEPATH . DIRECTORY_SEPARATOR . "application" . 
DIRECTORY_SEPARATOR . 'models/map/CategoriesTableMap.php'

Well, all we need to do now is use Propel! Keep in mind that using Propel’s classes directly from the controller is a bad practice, because you’d be coupling your data access layer to your presentation layer, you can take a look on this post if you want to read a bit more about it.

For our practical purposes we can just call the Propel query object from the controller now, much like this:

function index()
  $query = ProductsQuery::create()->limit(10)->find();
  $data =  array();
  $data['rows'] = $query;

  $this->load->view('welcome_message', $data);

And it will retrieve the results quickly and using a nice ORM mapper. I hope you’ve found this post useful and as usual commenting is highly encouraged!

New year!

New year starting, and I need to set up a few goals. First, I will be creating my own template, because like Scott Hanselman said, using a provided template in a blog might just look lame.

The second thing I need to do is post more stuff. I've been working on some cool stuff, and I think that I should post them, so people can see it and perhaps I can help someone out there!

That's the things I'm going to be working on this month to boost my blog a bit. Anyone who reads this, just wish u all a happy new year!