Booting Sharp Lite and autogenerating Db with nHibernate

When facing a new project, there are many things to consider, but there is no doubt that the words most mentioned and given more buzz are how to accomplish a scalable and maintainable solution without builing the next Amazon for our first version. However, trying to make a solution that is able to grow over time and adapt to new requirements is not an easy task, it’s indeed very tricky business. That’s why there are frameworks, mainly because there are a bunch of guys willing to help those who can’t (or won’t) get into building their own foundation to make a project.

And here is where S#arpArchitecture enters. S#arpArchitecture is project started by Billy McCafferty, a developer/architect well versed on the matter how made a super duper framework to deploy ASP .NET applications. The framework was consistent with several best practices he wrote on a CodeProject article on how to accomplish a nice setup of a project using nHibernate. The thing with S#arpArchitecture is that it was somehow a bit coupled into nHibernate, altough this didn’t seemed to matter at that point because nHibernate was (and IMHO is, but won’t get into that) the best way to accomplish ORM with a .NET project. However, time has changed and EntityFramework is a strong project, not to mention that is handled by the man, we also have now the NoSql fever and there are other stuff that may be yet to come and S#arpArchitecture had to evolve to remove the direct dependencies from nHibernate but as any old project moving away from the original idea has been a difficult business and the most important thing is that to be able t setup a S#arpArchitecture install using other thing than nHibernate, you’ll have to be very versed on topics such as IoC, design patterns, nHibernate itself, so you know what to remove and what not to remove and many other dark stuff.

Because of all these nasty reasons, Billy McCafferty decided to start yet another framework called S#arp Lite. The intention here was to be able to make a decent framework available for a broader audience of developers who didn’t had to be very versed on deep matters of architecture.

So, if you want to make an ASP .NET MVC 3 app and looking for a nice development framework, you should make a run for S#arp Lite and try it out. The first thing you’ll need is to read the blog post where Billy explains why he had to make S#arp Lite despite the fact that we already had a S#arpArchitecture, once you’ve read that, you should also get the basics on S#arp Lite also explained by Billy in this post. If, however, you don’t want to read any of those and just want to jumpstart into S#arp Lite, then the idea would be to:

Before anything, the sample app is found inside the S#arp Lite file downloaded from Github, on the folder called Example, the project is named MyStore. Now, to set up your database for the sample app, you can make two things, one I like it, the other not so much. Before getting to that, make sure that you have a SQL Server database to play with and get your connection string. Mostly if your DB is the integrated SQL Server Express DB that comes with Visual Studio, your connection string will look like this one:

Data Source=localhostsqlexpress;Initial Catalog=SampleDb;Integrated Security=True
 

The only thing that may change is the Initial Catalog, which is basically up to your choosing. Now that we know the connection string, we need to tell S#arp Lite what is it, so open the web.config file found on MyStore.Web and look for the line where says:

<connectionStrings>
   <add name="MyStoreConnectionString" connectionString="YOUR_CONNECTION_STRING" />
</connectionStrings>
 

And yes, you guessed it, change where it says YOUR_CONNECTION_STRING for the actual connection string.

Now we just need to setup our DB, for which you have two ways. The first way is the simplest one, which is to use a SQL server administration tool, the Management Studio Express included with the Express version of SQL Server express 2008 is just fine, and run the sql file you can find inside the example project on the folder called “MyStore.DB” et voilà! The project can now be run.

As a side note, the last time I downloaded S#arp Lite (v0.42), when setting up the sample project and compiling, you’d get 11 errors regarding tests and test classes that cannot be found, don’t despair! Just go into MyStore.Tests and remove the reference to nunit.framework and add it again, the assembly should be in your lib folder outside of the project. Now you can run the demo without issues!

Now the other way, which I like a lot more is to use nHibernate to generate your database, which is so cool! And since nHibernate is also very cool, this is a very simple process. Just go into your project called “MyStore.NHibernateProvider” and look for the class called NHibernateInitializer. Just like the name indicates this fellow handles the initialization of nHibernate and we will also generate the DB with it. Go into the class and add the method that will handle DB initialization:

public static void CheckAndBuilDb(Configuration cfg)
{
 var schemaValidator = new SchemaValidator(cfg);

 try {
  schemaValidator.Validate();
 }
 catch (Exception) {
  var schemaBuilder = new SchemaExport(cfg);
  //drop in case of old one
  schemaBuilder.Drop(false, true);
  schemaBuilder.Create(false, true);
 }
}
 

Without entering into unnecessary gory details, the idea is to check if the existent DB is up to date and if is not, drop it and regenerate a new one. This does bring a bad side effect, which is the issue of migrating from one version into another. That problem can be fixed doing some nHibernate-fu, but we won’t get into that for now. Build and run and your database will be automatically generating against the mapped entities! Cool uh?

This is pretty much just about it, I’ll make a follow up post with some more stuff on how to get going with S#arp Lite and Fluent nHibernate.

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;

@end
 

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:

#import 

//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;

@end  
 

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&lt;Product&gt;
{
 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()]
param(       
    [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
    [string]$DomainFolder,
    [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
    [string]$BaseEntity,
    [string]$Project,
 [string]$CodeLanguage,
 [string[]]$TemplateFolders,
 [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&lt;CodeProperty&gt;();
var enumerables = new List&lt;CodeProperty&gt;();
var references = new List&lt;CodeProperty&gt;();
 

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);
    mysql_close($link);
    
    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;
   }
   
   $this->dbConnector->OpenConnection();
   $count = $command->GetScalarValue();
   $this->dbConnector->CloseConnection();
   
   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));
$employeeTable->setRowClass('Employee');

$result = from('$employee')
 ->in( $employeeTable )
 ->where('$employee => strlen($employee->Name) < 5')
 ->orderBy('$employee->Name')
 ->select('$employee');
   
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 libsmarty. 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!");
       $smartyObject->display("hello.tpl");