Tip for a SVN project

May 9th, 2011

Ok, this is the scenario:

There is a huge project hosted on a SVN repo. I’m to start a new project based on that one… No, I’m not allowed to create a new branch. And I must upload this project to a new SVN repo.

So checking out the project is easy. Now that I have the project in my Mac I want to be able to check it into the new SVN repo, the only thing is that when I checked out the project it downloaded to mi machine with a whole bunch of “.svn” folders.

Now, there are 2 different ways to get a clean copy of a project from a repo.

1. Do an export instead of a checkout, this will give you a project copy without the annoying “.svn” folders.

2. Do a regular checkout and then delete all the “.svn” folders.

On my humble opinion it’s better to do an export. If you do a checkout you can delete the “.svn” folders manually but be aware if you have lots of folders because an “.svn” folder will be created within each of your project’s folder so if you have a project with 10 folders and each one with two subfolders you’ll have to go into each f them to delete the “.svn” folders manually… it’s easy but it might take a lot of time and resources you might not have.

To speed up things it’s better to do the following:

Go to your project’s folder and run the following command:

find . -name ".svn" -type d -exec rm -rf {} \;

It will search for all directories called “.svn” and delete them as well as it’s contents.
I found this to be very useful and I really use it frequently but I keep forgetting it so I’m posting it here 😀

Forms and encoding

May 8th, 2011

Ok, Zend Framework has lots of components to do almost anything.
One of the coolest is the form component, it reduces the time spent coding a form and it’s validation and you can then reuse the form code wherever you want and it will behave exactly the same.
One thing was annoying me. When in a form element label you use accents the label, once parsed, will display either weird characters or the raw html code.
For example take a look at this code:

$this->addElement('text','email',array(
            'size'=>'50',
            'label'=>'Correo Electrónico*',
            'required'=>true,
            'validators'=>array('NotEmpty','EmailAddress')
            ));

I wanted it to read: Correo Electrónico, but instead of ‘ó´it was displaying a weird character or the raw html code for an accented ‘o’ (ó) so I was wondering how can I solve this. It didn’t take me a lot of time to figure this one out, the solution was simple and elegant. When declaring a form element there is a flag that will handle if the label gets escaped or not.

The only thing I did was to change the element declaration from the former to this:

$this->addElement('text','email',array(
            'size'=>'50',
            'label'=>'Correo Electrónico*',
            'required'=>true,
            'validators'=>array('NotEmpty','EmailAddress'),
            'escape'=>false
            ));

That’s it, it works.
Oh, BTW, I have my encodings set to ‘utf-8’, if you have ‘iso-8859-1’ you may leave your accents without encoding as html.

Zend Server – Mac OS issue with MySQL

May 3rd, 2011

So I finally decided to install a dev env in my Mac.
A couple of days I installed Zend Server on my Mac but I wasn’t too convinced about installling a dev env in my Mac so I uninstalled Zend Server as I thought was the proper way to do it: Drag the Zend Server from apps to the trash.
So yesterday I finally made up my mind and decided to go along with a dev env. Since the first install went smoothly I thought it would only require me to do exactly the same thing…. WRONG!!!!
I downloaded the package and ran the installer, no error messages were displayed, I even opened the Zend Server console and it worked, I even tested a few scripts and it was doing fine.
Next thing I wanted to do was to create a database in MySQL and this is when my headache started.
First time I installed Zend Server I realized it wasn’t enable to work as a network server, by default you can connect to it by a socket which is fine if the server will only run on your machine… Honestly I didn’t have any problems with it… the problem was that apparently MySQL wasn’t working.
Ok, calm down, don’t panic. I thought it had something to do with socket permissions… WRONG!
mmmm ok, what exactly can be the problem?
I opened a console and typed:

sudo [path_to_zend_bin]/zendctl.sh restart

Apache did ok, Zend Server GUI (Lighthttpd) did ok but MySQL didn’t…. it showed the following message:

ERROR! MySQL manager or server PID file could not be found!
Starting MySQL
. ERROR! Manager of pid-file quit without updating file.

What in God’s name does that mean????
I searched it in Google, apparently I’m not the only one experiencing the issue. It looks that there were a lot of different solutions but none of them worked for me :(…. Now I really wanted my Zend Server to work, and I’m stubborn so I kept searching, went to the forums (official MySQL forums) and nothing. By that time I was both mad and sad. I tried deleting files, reinstalling, changing owners and NADA!
Finally, since it was already to late and I was falling asleep I decided to leave it for “tomorrow”.
I even dreamed about this not being solved hahahahaha.
Anyway the next day I relaxed, saw a couple of videos on youtube and finally came up with the most easy solution to this in a blog.
In a few words this meant that me dragging the Zend Server app to the trash can is not the proper way to uninstall it. I have to use the following command:

sudo /usr/local/zend/bin/uninstall.sh

It was the only thing I didn’t try so I typed it and hit enter…. this got the job done!!! :O
OMG! it was sooooo simple, I felt stupid hahahahahaha
So I’m posting it here to remember it.

PHP classes autoload (namespaces) Part II

April 20th, 2011

Ok so I made a few tests.

As a matter of fact I think it is better to use the function I wrote about in my previous post.

Turns out that I removed a couple of lines and added some more. At the end I decided to use the set_include_path because it’s more suitable for documentation purposes as well as configuration.

So after a few minutes I came up with this:

define('CLSS_PTH','path_to_classes_folder');
define('NMSPCS_PTH','path_to_namespaces_folder');
set_include_path(get_include_path() . PATH_SEPARATOR . CLSS_PTH);
set_include_path(get_include_path() . PATH_SEPARATOR . NMSPCS_PTH);

function __autoload($class){
    $class = strtolower($class);
    if(strpos($class,'\\')!==false){
        $class = preg_replace('/\\\/',DIRECTORY_SEPARATOR,$class);
    }
    $possibilities = explode(PATH_SEPARATOR, get_include_path());
    foreach($possibilities as $path){
        if(file_exists($path . DIRECTORY_SEPARATOR . $class . ".php")){
            require_once $path . DIRECTORY_SEPARATOR . $class . ".php";
        }
    }
}

So I added a path where to look for classes and namespaces, afterwards we go through all of those paths searching for the file. Works like a charm!

PHP classes autoload (namespaces)

April 20th, 2011

I like PHP, OOP is very easy with it and Zend Framework is a charm once you start to get use to it.

One of the coolest things in the latest release of PHP are namespaces, really they are cool! Weird as it may sound coding in PHP reminds me of Java ;P Namespaces allows me to give some order to my code and avoids overwriting other code, it’s pretty neat but one thing I’ve been meesing around is autoloading namespaced classes.

After a few hours I’ve managed to code a simple classes and namespaces autoloader, it’s the first version so I’ll be enhancing it over the next days.

I’ll try to make it as clear as possible. Code will be commented. Hope it helps someone 😀

Ok there are two kinds of files I want to autoload: namespaced classes and normal classes.

For both of them I’ll need a path:

define('CLSS_PTH','path_to_classes_folder');
define('NMSPCS_PTH','path_to_namespaces_folder');

Now to the function!

For standarization purposes class names can be camelcase but when searching the file’s name it must be lowercase.

I’ll code the body of the autoload function provided by php.

function __autoload($class){
  $class = strtolower($class);
  if(strpos('\\',$class)){
    $class = preg_replace('/\\/',DIRECTORY_SEPARATOR,$class);
    require_once (NMSPCS_PTH . DIRECTORY_SEPARATOR . $class . ".php");
  }
  else{
    require_once (CLSS_PTH . DIRECTORY_SEPARATOR . $class . ".php");
  }
}

That’s it… now I just read about a php function called set_include_path and just saw other way to autoload classes… I’ll leave that for version 2 hehehe

.htaccess maintenance

April 13th, 2011

Again a while since the last post but honestly I have a lot of work to do, fortunately one of the projects I’m involved requires me to learn Python.. at last!

Anyway, one division of the company hired a third party to develop a web page. The provider finished the development and finally sent everything to us. It was a php webpage, it uses the Cake Framework and MySQL so everyone thought it was going to be very easy to release the webpage in the company’s server.

A few weeks before today we decided to order the site folder and create special boxes for mini sites and small projects, even though url may seem as if the folder is directly under the web server root, it isn’t. This is cool because it keeps things from being a mess and maintenance becomes pretty easy.

So, as I was saying, we got the scripts for both the site and the database. Database was easy, we just imported the sql file and voilá! done!

The problem rised when we got to the site’s scripts. We typed the url correctly and ¡nothing! so we were surprised, everything was working fine so it wasn’t possible for a single site not to work. We read the logs, enabled the debug and nothing raised. After a few days we decided that the provider should help us. So he happily agreed to bring his people to help me…. same result. Something strange was happening, finally the provider quit and told us that the development was working on their servers and they were happy with that…. sorry :s

I got mad because of this but my boss and I decided we should dig this in. After a few days we found the cause of the problem. When we ordered the web server folders we enabled an alias to a folder. Cake uses htaccess files to provide MVC functionality. When we enabled the alias folder we forgot to enable htaccess parse, duh! so we learned that each directory that will be included on a web server should have a conf line like this:

<Directory /absolute/path/to/alias/folder>
Options -Indexes Includes FollowSymLinks MultiViews ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>

We added the proper lines, modified the htaccess rewrite rules to support 2 different domains and now everything works.

We keep learning everyday 😀

Ad Vitam Paramus

Zend Framework 101

February 8th, 2011

Ok, it’s being a while since I last published something here.

I’ve been digging into Zend Framework trying to understand everything so I can code easily. So far I’ve discovered that way too many PHP programmers get confused about three basic definitions.

Zend Framework

As stated before, Zend Framework is a library with a bunch of classes for almost everything (Auth, ACL, DB connections, etc.) this is important, cause I’ve noticed that way too many PHP programmers are confused with ZF being a new way of coding and setting up your application.

With pure Zend Framework you may use any class you want whenever you want to use it, just be sure to include the ZF library path and you’re done.

MVC

Now, while reading about ZF programmers may found a lot of talk about MVC, this stands for Model-View-Controller which is a coding paradigm I won’t explain cause there’s a lot of info about it in the web (Google it).

Here is where you start dealing with the bootstrap, configuration file, error handling and main setups.

ZF Tool

This stands for Zend Framework tool which basically is a bat/bash script that you may use from the command line to automatize some coding if you’re using Zend Framework and MVC. It’s pretty useful and you have the possibility to modify/enhance this script as you wish. If you won’t be coding with MVC you might as well forget about this tool.

Having these three basic definitions we can start discussing the framework. ZF, as I already stated, has a bunch of useful classes which are very simple to use. I know some of you will raise your voice and argue that it isn’t and that you have to place code in the bootstrap and then make a later call in a model and it might become confusing, if so let me remind you that right now I’m just writing about the ZF not being used within a MVC coding paradigm. By this I’m trying to make you understand that ZF can be used to code applications as you being doing for years as long as you are used to OOP.

Let’s see an example of how ZF helps you code faster. I’ll do a simple auth script.

I wont be pasting any HTML or javascript code, I’m assuming you can figure those out.

So, suppose you have a form that sends the login and password to dologin.php, in the php file you’ll have something like this:

<?php
/***********
Include's, require's, session's code.
**********/
/* After receiving, validating and filtering your input you'll define where do the user credentials are stored */
$login = $_REQUEST['login'];
$password = $_REQUEST['pass'];
//Create a database adapter
$dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter();
//Create the auth adapter
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
//Configure the auth adapter with the proper table name and credential fields.
$authAdapter->setTablename('users')
->setIdentityColumn('login')
->setCredentialColumn('password');
//Give the auth object the info to validate
$authAdapter->setIdentity($login)
->setCredential($password);
//Call the auth instance
$auth = Zend_Auth::getInstance();
//Validate
$result = $auth->authenticate($authAdapter);
//Some code to process the response
if(!$result){
//Go to login, credentials are wrong
}
else{
//Store identity
//Get user data, but avoid retrieving the password
$userData = $authAdapter->getResultRowObject(null,'password');
//Write data to auth object so object is modified
$auth->getStorage()->write($userData);
}
//Do more stuff
?>

So that’s it for the login. It’s pretty simple, and you can make it even more complex by adding some constraints, for example a user row that indicates if that user has been deactivated (Play with it and read the ZF documentation regarding this).

Now let’s say you want a page only to be available for logged in users. You won’t need to authenticate again your user, just call the auth object like this:

<?php
//Some code of your own
//Get auth object
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()){
echo('You\'re in!');
}
else{
echo('Ooops! sorry, you need to login first');
}
?>

So there you go, quite simple isn’t it.

Hope this helps you start playing with ZF. I’ll post more stuff in the go.

Thoughts on Zend Framework

October 21st, 2010

Well I’ve jumped into the Zend Framework development… finally!

At first glance it looks like a mess, create the environment, separate models, views and controllers, configure the app, the bootstrap…. When I started working here (my current job, which I can’t give the name due to the terms of my job contract) I was hired because of my knowledge of PHP. Business owners stated that they needed a high profile PHP programmer. They said they were moving towards PHP development under Zend Framwork. Cool! a new learning experience.

I must say that when I got here I wasn’t familiar with ZF so it was a whole new experience. Days went by, and anfter a couple of months I have realized what is Zend Framework and why everybody thinks it’s too complicated. There is a big confusion even from Zend.

The confusion begins from the ZF tutorial. They start explaining you about MVC… here’s the whole confusion.

Zend Framework is a set of libraries that can help you with RAD, it has nothing to do woth MVC paradigm.

MVC is a coding paradigm, such as the three layers paradigm. You can code your whole application in whatever paradigm you wish and still use Zend Framework, but Zend treats both the paradigm and the set of libraries as the same. I’m not arguing that something is wrong, what I’m saying is that Zend Framework is one thing and MVC coding paradigm is a whole different one.

Do not be confused! MVC & ZF are a great, neat way of doing things but, as every technology, you should evaluate if both are needed for every project. If you are coding a simple web service then you might not need to use MVC but still use the framework to RAD.

Do a little research, clarify your needs and make the perfect choice for the case you’re dealing. Sometimes MVC can create a lot of garbage folders and files that wont be used at the end of the day.

Remember: KISS (Keep It Simple, Stupid)

Code maintenance

October 20th, 2010

Keeping track of code through time is a very delicate task.

It gets to be a really important issue when customers are making usability tests to a program. You make some changes, the customer reviews them, approves and you send them to production, a couple of days later the customer changes his mind and ask you to go back to how the program looked 3 months ago.

That scenario gets to be very common in web development and can be a serious problem if you don’t give your customer what he wants. How could you go back to a 3 months old version of a page? Did you backed up your files? Is your presentation layer different from the logic one? What has changed since then? How can I merge those changes?

Changes are part of software life, so they must be documented properly. Changes documentation should answer the following:

Who made the change? If something goes wrong you may identify who made what and the settle responsabilities.

What changes were made? You should keep track of what files were affected, what code lines were modified and what was changed in the logic.

When were those changes made? You’ll keep track of time invested on that change.

Why? Was it because of a user request?, a bug fix?, an enhancement?

If you work for a company answering these questions will prove to be a great way to justify your work. It will even make it easier for your colleagues to keep up with your coding style and logic.

Most developers use inline comments to document changes for example:

/**

* author: Me

* date: October 25th 2009

* version: 1.0.1

* summary: User asked for the color to be changed from red to blue so the code changed from $color = “red”; to current

*/

$color = “blue”;

That’s a nice way to keep track of changes but you’ll get to the point that one change requires a lot of file content modifications, folder creations, code logic changes, etc. which on large projects can be a real hell to keep track of. This just happened recently on my job.

We solved a lot of things by using a version control software. We tested it and finally decided to go for SVN or subversion. It’s pretty easy.

Even though projects creation and repositories administration were a mess at the begining because we wanted to limit access to developer groups only to their assigned projects. We kept SVN and installed USVN on  top of it…. needles to say we are very very happy with the results.

We get to admin our repositories in a very simple way. Since USVN is developed in PHP Zend Framework and you get to modify the code we have made some customizations to it so it works as we want it to work.

One great thing we managed to do with SVN is have a strict control over our stage environment. Developers do a SVN commit which immediately updates a stage environment so changes are visible to QA.  Once QA approves a version we create a tag meaning its a new release which then goes to production.

That’s the main reason I’m posting this, I was the one responsible for implementing those automations and they do work.

How did I do this? Well it’s actually pretty simple. Once a SVN project is created you go into that project’s folder and go to the hooks subfolder. This is where the magic happens.

Though there are several types of hooks I only messed with the post-commit hook.

I granted execution permissions to post-commit file (remove the “.tmpl” part).

Modified the hook so its aware of some important paths and then coded a few lines so, for example, we got SVN to send an email reporting what changed, who did the changes and when was the code commited to project owner so he could keep track of his project.

SVN works for us right now and hooks are a charm. I’m pleased right now and so are my boss and my colleagues :D:D:D:D

I keep repeating to myself: Linux rocks, free software rocks and most of all I rock! hahahahahaha

PHPMailer & Hotmail showing an empty or blank screen

July 27th, 2010

Yes, as it reads.

I’ve been using PHPMailer class for a while but only a few days from now I received a complaint from a customer that told me he got an empty email with his order confirmation.

At first I assumed he was the only one experiencing this so I told him to tweek his Hotmail account or move to Gmail, Yahoo or a better service provider. Next thing I knew a couple more customers sent me an email with the same complain.

So, it’s only happening with Hotmail… Time to do some tests.

To my surprise email was arriving to destination address but it was showing nothing, it was a blank/empty email body. No way! somethings gotta be wrong! I right clicked the message and selected the view source option.

Ok, message content was there so something else is happening. Email headers, boundaries… something is causing the email not to be shown.

After a couple of days of searching and testing I came to this simple solution.

Go to phpmailer.class.php

Then search for code lines that look like this:

$result = ”;

switch ($this->message_type) {

case ‘plain’ :

$result .= $this->HeaderLine ( ‘Content-Transfer-Encoding’, $this->Encoding );

$result .= sprintf ( “Content-Type: %s; charset=\”%s\””, $this->ContentType, $this->CharSet );

break;

case ‘attachments’ :

case ‘alt_attachments’ :

if ($this->InlineImageExists ()) {

$result .= sprintf ( “Content-Type: %s;%s\ttype=\”text/html\”;%s\tboundary=\”%s\”%s”, ‘multipart/related’, $this->LE, $this->LE, $this->boundary [1], $this->LE );

} else {

$result .= $this->HeaderLine ( ‘Content-Type’, ‘multipart/mixed;’ );

$result .= $this->TextLine ( “\tboundary=\”” . $this->boundary [1] . ‘”‘ );

}

break;

case ‘alt’ :

$result .= $this->HeaderLine ( ‘Content-Type’, ‘multipart/alternative;’ );

$result .= $this->TextLine ( “\tboundary=\”” . $this->boundary [1] . ‘”‘ );

break;

}

Do you see the line where it reads: multipart/alternative

Change that into multipart/mixed

That’s it! Hotmail will display your AltBody content!

It worked for us so if it doesn´t work for you, then better start messing with the headers 😀