What have I been up to recently…

Last month was an action packed month for me. I had a few events going on and lots of work to get done.

Atlanta PHP User Group

We had a really cool presentation on load testing using JMeter and Xdebug by Brian DeShong. Load testing and profiling are very important to help identify possible bottlenecks in your application/server before reaching a breaking point. JMeter allows a user to setup different scenarios to run with varying loads (number of users, ramp up time). It’s pretty fancy with all the options you can do such as submit variables to pages to simulate login ins to an application and tracking sessions. Xdebug lets us analyze logs to see what was going on in your application to easily spot which part of the execution process took the most amount of time. At that point, you can look at your code to see how to improve that particular process.

At work we have an outside firm doing our testing/load testing so it was nice learning about JMeter so eventually we can start doing some of our own load tests for things we need done asap. I currently use Zend Studio’s profiler to profile my applications so I probably won’t be using Xdebug any time soon.

TEK-X

I asked around our local user group what conference they would recommend if they could only attend one PHP conference and this was the one I heard the most good things about. This was my first time attending a PHP conference and it was WELL worth it. The sessions were great with three tracks daily to choose from. The conference was small enough where you could spend time with the presenters interacting and asking questions. I met a bunch of new people which made the whole experience that much better. There was always something to do during presentations as well as after hours.

This is the web site for TEX-K if you want more info or want to take a look at the schedule. Some of my favorite were the two Flex sessions by Keith Casey since I want to start doing more Flex and the Lost Art of Simplicty by Josh Holmes was interesting as well. It was really nice having a bunch of Adobe and Microsoft people there. They were all great and helpful. We had been having some server hiccups at work and the guys at Microsoft were extremely helpful in trying to help us figure things out. We also learned from various people (both the MS and PHP crowd) that we (at work) should start using IIS instead of Apache for Windows. Microsoft has been spending resources in working with the PHP team to make sure things run smoother with PHP on IIS for Windows than before.

Two thumbs up for Microsoft and Adobe for being there and supporting the community (and for the drinks and dinners :p) . I’ll definitely try to go next year again.

Flash Builder for PHP

I took a one day-8 hour course on using Flash Builder and wow… I’m sold. After working on Flash for so many years, Flex is just too amazing to ignore. The class was taught by Adobe certified Jeanette Stallons and it was a small class which was great for us since we could get a lot more time for questions and one on one time. She did a great job keeping our attention and was very easy to follow. This was a hands on class so we each had our own computer to work the examples with.

The class started with us learning about the different Adobe applications, the difference between Flash/Flex, and reasoning behind changing the name Flex builder to Flash builder. Then we went through the basics of the IDE and how to setup a project and what the different folders and files are for. Next is when things got fun. We started creating an application that communicates with the database through PHP. We did all the code manually to better appreciate the last lesson which was creating the exact same application in an automated fashion with literally only a few lines of code at most. That was the coolest part of this class, how easy it is to use the wizards (that actually spit out good code!) to be able to just click and drag and have everything working correctly in such a short amount of time.

I already downloaded the two month trial from the Adobe’s site and have been playing around with Flash Builder at work and at home.

Google AdWords API v13 to v2009

A few years ago I wrote an application that heavily uses the Google Adwords API. It worked without me touching it for years until recently Google changed their Adwords API and my app completely stopped working. This was my fault of course since many months ago Google emailed me letting me know this was going to happen but at the time I figured there wouldn’t be much difference between both versions so I didn’t pay much attention to it… boy was I wrong.

The new API v2009 is very different since you call things differently now and many of the old services I was using no longer exist in the new version. I spent some time trying to rework my code to use the new calls but that was not working well for me. It just seemed as if I was wasting time instead of just starting over with a clean rewrite. Fortunately for me, after doing some research, I found that Google had already created a client library for PHP that already did all the heavy lifting code to interact with the services. I downloaded the library, ran a couple tests and everything was working perfectly. All I had to do was rewrite the application using the client library and everything is running smoothly again.

Thanks Google! You saved me a lot of time but don’t change your API again 😛

My Birthday

Not much to mention here other than it was my birthday last month as well so had dinners with parents and drinks with friends. I have been running a lot lately so I bought myself a nice new watch with my birthday money: Garmin 405. I saw this watch on sale on slickdeals.net for under $200 and I couldn’t resist. I’ve used it a couple times already and it’s great. The GPS seems to be working flawlessly for me so far and all the features it brings are neat to play with. My biggest sellers were: GPS to track my distance and pace and the heart rate monitor.

Peachtree Road Race, here I come!

Two thumbs up for the wifey!

So my wife submitted a design for an eco-friendly bag contest for Kroger late last year. There were over 46,000 entries nation wide and she ended up winning second place!!! Great job sweets!

Starting next month (April), if you shop at Kroger, you may be able to purchase her bag from your local Kroger store. Here is an article that just came out today from a local magazine:

http://www.mdjonline.com/view/full_story/6794712/article-Marietta-graphic-designer-takes-2nd-in-Kroger-s-reusable-bag-competition?instance=home_news_1st_right

Feel free to visit Ashley’s blog and let her know she did a great job: Ashley’s Blog

My Dale Carnegie High Impact Presentations Experience/Review

Wow… I can’t stress enough how much improvement I made over the course of two days from taking this program from Dale Carnegie. Before I continue with this post I want to thank Julianne Rivera (Sr. Business Consultant) for encouraging me to take this class. Had it not been for her, my audience would have paid the price. I also want to thank Ercell Charles and April Farlow for being great coaches throughout this program and doing a fantastic job. This was my first time taking a Dale Carnegie class and it won’t be my last. Make sure to watch the before and after videos below to see why.

Why did I want to take this class?

Every time I receive a comment on this blog from my users letting me know that what I wrote helped them in some way, I find it extremely rewarding. I like being able to share my thoughts, knowledge, and experience with others and have decided I want to start presenting to local user groups to further expand my reach. I know my material, but my presentation skills were lacking. I have my first presentation coming up for the Atlanta PHP User Group and I want to make sure I don’t bore my audience. I did a quick dry run to test my presentation and it wasn’t very energetic… it was actually pretty dull. So when the opportunity to take a Dale Carnegie class on presentations presented itself, I took it. Continue reading “My Dale Carnegie High Impact Presentations Experience/Review”

Using Zend_Paginator with Twitter API and Zend_Cache

Zend Framework 1.10.0 is out and a comment was posted on my blog that lead me to creating this new post. I’m going to focus more on Zend_Paginator and Zend_Rest_Client to access Twitters API since I’ve already created a post on Zend_Cache. Normally, I would use Zend_Service_Twitter to access the twitter service but it still seems to require authentication to retrieve a users timeline where only protected users should require authentication.

Zend_Paginator

Zend_Paginator from the Zend Framework site:

Zend_Paginator is a flexible component for paginating collections of data and presenting that data to users.

Zend_Paginator automatically creates pagination for you by setting up a few parameters and passing it an array of data. What is pagination, if you have ever gone to Google and searched for anything, usually you’ll see something like the following at the bottom of the search results page:

See the numbers and the text links, this is called pagination. So much data exists for the particular search that it wouldn’t make sense to display it all in one page. It would cause large amounts of scrolling down to view, the load time of the page would be affected, so we rather show fewer results and give our users the option of viewing more by clicking on the pagination links.

To demonstrate how to use Zend_Paginator I created a sample Zend Framework 1.10.0 application. This application grabs my last 50 tweets using the Twitter API and displays them 10 at a time using Zend_Paginator. I use Zend_Cache to cache my twitter data so I don’t have to spend time accessing their api every time – I’m sure they would appreciate it.

Bootstrap

The first step was to create a new zend framework project. I’m making the assumption that if you are reading this then you already know how to do this. After creating my new project, I added two methods to my bootstrap file to autoload and to init Zend_Cache. My bootstrap looks like the following:
Continue reading “Using Zend_Paginator with Twitter API and Zend_Cache”

Finally gave my blog a much needed face lift!

So what do you guys think? Does it look better now? It is not finished, I still need to tweak some graphics and colors but overall I’m very pleased. I started out with a new theme: Arclite by digitalnature. It has many customization options so I haven’t had to do too much tweaking of the .css files but there has been some. Since I blog so much about code, I finally stopped being lazy and got a code highlighter. I’m using: Dean’s Code Highlighter by Dean Lee. It’s very easy to use and supports a range of different code syntax such as PHP and Actionscript. One of the reasons I decided to update my look was because I have been running an older version of WordPress and it was about time to upgrade. I’m now running 2.9.1 and it looks great. I really like the new admin back office and it is so easy to use and setup.

I also created my first widgets! The ‘Interesting Links’ and ‘Interesting Images’ on the sidebar are no longer hacks done on the themes sidebar.php file. I learned how to create a plugin in WordPress and make it into a widget. Here is what one of the widgets looks like:

/*
Plugin Name: JR-Images
Plugin URI: http://www.joeyrivera.com
Description: Show my images
Version: 0.1
Author: Joey Rivera
Author URI: http://www.joeyrivera.com

  Copyright 2010  Joey Rivera  (email : joey1.rivera@gmail.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
 
function show_images() 
{
	global $wpdb;
	
	$query = '
		SELECT image_file, image_origin, image_thumbnail
		FROM wp_images
		ORDER BY image_id DESC
		LIMIT 6';
	
	$results = $wpdb->get_results($query);
	
	if(!$results)
	{
		return;
	}
	echo '
  • Interesting Images

    '; echo '
      '; foreach($results as $row) { echo '
    • ', "\n"; } echo '
    '; echo '
  • '; } function register_images() { register_sidebar_widget("JR-Images", "show_images"); } add_action("plugins_loaded", "register_images");

    I had to go back to all my old posts and make updates. If you find any issues anywhere, please let me know so I can fix it asap. I’ve found instances in code where there should be two && and instead the code blocks shows &&. I’m currently trying to figure out why my preview button doesn’t work, hopefully I’ll figure that out soon so I can move on to changing some colors around and finally updating my ‘About Me’ page. I hope to have some content in that page by the end of this weekend. Other than that, I hope you all enjoy the new look and am looking forward to hearing some feedback!

    Automate Db Model Creation with Zend_CodeGenerator_Php_Class

    I’m working on a new tool at work that will automate several processes for a few employees so they don’t have to spend too much time doing very repetitive tasks. This tool has to do a good bit of database manipulation so I’ve decided I’ll build it in PHP using Zend Framework.

    I’ll be using Zend_Db_Table_Abstract to communicate with the db tables from my project and I’ll be creating a model for each table as well to store and manipulate data. I’ll be working with lots of tables in the database and many have lots of fields.

    I start by opening up Zend Studio on one monitor and SQL Query Analyzer on the other and get to work. The first table I want to work with is the ‘Student’ table. I create a new file in my project called Student.php. Place it on my models/DbTable folder and inside I simply have to declare ‘_name’ as a protected property with the value ‘Student’ and extend ‘Zend_Db_Table_Abstract’. Easy enough but now I want to create the model I will be using to convert the database data into workable objects through my mapper class.

    Problem

    I create a new file called ‘Student.php’ and save it to my models folder. I open the file up and now I have to create a property (it’s actually an array _data with all properties defined as keys inside) for each field in the Student table… all 50 of them! I have to be careful to name each correctly as well as to not accidentally miss some field. It ends up being a time consuming process and inefficient so I start looking for a better way to accomplish this. Continue reading “Automate Db Model Creation with Zend_CodeGenerator_Php_Class”

    Caching using PHP/Zend_Cache and MySQL

    I like the definition used in Wikipedia: “a cache is a temporary storage area where often accessed data can be stored for quick access”. The idea is to get ‘often accessed data’ from a database and store it in memory (RAM or as a file in your local file system). This is because:

    • it’s quicker for a machine to read from memory than to connect to a database and query data.
    • it’s more efficient for the database to not waste time and resources returning the same dataset multiple times when it could be focusing on other tasks.

    As long as the data, in this scenario from the database, doesn’t change, there is no need to query it again.

    Resources are limited on systems and to take advantage of your resources, you need to make sure time isn’t spent on tasks that could be handled better elsewhere. Here is a silly real world example. Imagine on a daily basis, I have to track how many magazines I have and send this information to Person X. I get new magazines at the beginning of each month only. To track the number of magazines I have every day I could

    1. Count them, one by one every day and send Person X the total. If I have 50 magazines this could take some time and assume I get 10 more every month, after a year or two I could spend all day just counting how many magazines I have instead of working. Sound productive?
    2. Count them once and write the number down on a piece of paper (caching!). Everyday when Person X asks how many magazines I have, I read the number from the piece of paper. Only when I get new magazines (once a month) do I count them again (or just add the current number + the new amount) to get my new total. Then I update my piece of paper with the new total (updating the value in cache).

    The latter is definitely the more productive choice.

    The same idea applies to computer systems. In the web, you have static and dynamic files. Static files are quicker to serve on a server because the server only has to read the contents of the file and send it to the browser requesting it. Dynamic pages take more time and resources because the server needs to execute the code in the page and only once it’s done can it send the request back. PHP can be used to create dynamic pages. The server executes the php code and spits out a file that then is read by the browser. If a database is involved, then the database has to run it’s task as well before the final file is returned.

    When ever possible, it’s more efficient to serve a static file or static content. We use cache to accomplish this. In this post I’m going to talk about caching files and database queries to local files on the server. Continue reading “Caching using PHP/Zend_Cache and MySQL”

    Implementing Vanity URLs in PHP w/ Zend Framework

    One of the reasons why people like vanity url’s is because they are easy to remember. For example take the following url:

    http://www.somesocialsite.com/?user_id=123456789&page=somepage

    If this was the url to my page in some social network site, there’s no way I could remember it nor would I be able to easily share the url with others unless I sent them the link. Now, if I could instead create a vanity url that looked like the following:

    http://www.somesocialsite.com/joeyrivera

    it would be much easier to remember and to share with others. Not only that but now I have a much more search engine friendly url with keywords that I would like to be found under – but ignore the search engine benefits for now.

    Why

    I’m currently working on an application that can benefit from vanity urls for the reasons mentioned above so I decided to spend some time thinking of ways to implement this. The first way that came to my mind was using mod_rewrite. Mod rewrite lets you manipulate urls. For example, you can write rules in your .htaccess file so when a user goes to http://www.somesocialsite.com/joeyrivera it really calls http://www.somesocialsite.com/search.php?user=joeyrivera or in zend the request would be more like http://www.somesocialsite.com/search/user/name/joeyrivera Continue reading “Implementing Vanity URLs in PHP w/ Zend Framework”

    Extract collections of similar objects from an array in php

    A co-worker was working on some stuff dealing with creating collections of objects within an array so I decided to play around with the idea. Basically, you start with a big array filled of objects and the objective is to create smaller arrays of similar objects. In this case we want collections of person objects who names are the same. Here is what I came up with:

    <?php
    
    class person
    {
    	public $id = null;
    	public $name = '';
    
    	public function __construct($id, $name)
    	{
    		$this->id = $id;
    		$this->name = $name;
    	}
    }
    
    $persons = array();
    $persons[] = new person(1, 'bob');
    $persons[] = new person(2, 'bob');
    $persons[] = new person(3, 'moses');
    $persons[] = new person(4, 'joey');
    $persons[] = new person(5, 'bob');
    $persons[] = new person(6, 'joey');
    $persons[] = new person(7, 'bob');
    $persons[] = new person(8, 'moses');
    $persons[] = new person(9, 'joey');
    $persons[] = new person(10, 'joey');
    
    $collections = array();
    
    // loop until there are no person left in array
    while(count($persons) > 0)
    {
    	// new collection and insert first person from array
    	$collection = array();
    	$collection[] = $persons[0];
    
    	// now remove person from array since already in collection
    	array_shift($persons);
    
    	// loop through each person in array
    	for($x = 0; $x < count($persons); $x++)
    	{
    		// check if there is a match
    		if($persons[$x]->name == $collection[0]->name)
    		{
    			// add person to this collection
    			$collection[] = $persons[$x];
    
    			// pop if last item
    			if($x+1-count($persons) == 0)
    			{
    				array_splice($persons, $x);
    			}
    			else
    			{
    				array_splice($persons, $x, $x+1-count($persons));
    			}
    			// move back since array position gets deleted, else will skip over next index
    			$x--;
    		}
    	}
    	$collections[] = $collection;
    }
    
    debug($collections);
    function debug($o)
    {
    	echo '<pre>';
    	print_r($o);
    	echo '</pre>';
    }

    And the result is:

    Array
    (
        [0] => Array
            (
                [0] => person Object
                    (
                        [id] => 1
                        [name] => bob
                    )
    
                [1] => person Object
                    (
                        [id] => 2
                        [name] => bob
                    )
    
                [2] => person Object
                    (
                        [id] => 5
                        [name] => bob
                    )
    
                [3] => person Object
                    (
                        [id] => 7
                        [name] => bob
                    )
    
            )
    
        [1] => Array
            (
                [0] => person Object
                    (
                        [id] => 3
                        [name] => moses
                    )
    
                [1] => person Object
                    (
                        [id] => 8
                        [name] => moses
                    )
    
            )
    
        [2] => Array
            (
                [0] => person Object
                    (
                        [id] => 4
                        [name] => joey
                    )
    
                [1] => person Object
                    (
                        [id] => 6
                        [name] => joey
                    )
    
                [2] => person Object
                    (
                        [id] => 9
                        [name] => joey
                    )
    
                [3] => person Object
                    (
                        [id] => 10
                        [name] => joey
                    )
    
            )
    
    )

    You start with 1 big array and end up with, in this case, 3 arrays of person whos names are ‘bob’, then ‘moses’, and finally ‘joey’.

    SQLSTATE[HY000]: General error – using php/pdo mysql stored procedures (sp)

    I spent many hours last night trying to figure out why I was getting a fatal error: ‘SQLSTATE[HY000]: General error 0’ in my code and finally figured it out but first my environment. I’m using Zend Server CE running php 5.3.0, zend framework 1.9.0 and mysql 5.1.32. I should have tested this bug without the zend framework to make sure it’s not specific to zf (I don’t think it is) but I’m feeling lazy so I’ll let someone else try it out.

    My code works as follows. I have a php class that calls a stored procedure which will take in an id, return a record set (if found) and will also return 2 out variables. While it was returning a record set everything was working perfectly fine. When I tried passing an invalid id, nothing was being returned and my code would keep giving me the ‘SQLSTATE[HY000]: General error 0’ (very helpful error indeed…).

    The issue ended up being the way I had my stored procedure coded. I would first check to see if the id passed was valid, if so I would select the data else I would set my out vars to some value and do nothing else. For some reason, because I wasn’t returning a select, my code would blow up. In the mysql query browser, my stored procedure worked fine and my second select to get the out vars was working correctly. But php didn’t like it one bit. I tried forcing a select in my stored procedure in the invalid id section and then everything worked fine again. This sounds a bit confusing so here is the way I can replicate this. Continue reading “SQLSTATE[HY000]: General error – using php/pdo mysql stored procedures (sp)”