Setting Up Your Magento Scripting Environment

One of the things that I do quite often in Magento is write scripts to accomplish certain tasks. Mostly these tasks involve me updating prices, creating a sale, or fixing a data problem in products. The code base for Magneto is heavily object oriented which makes it incredibly easy to pull in the full power of Magento and use it in outside scripts. Continue reading Setting Up Your Magento Scripting Environment

Getting and Setting Session Variables in Magento

Working in the Magento ecosystem can seem daunting at first. Even experienced PHP programmers have a steep learning curve to work through before they really get the sense that they know what they are doing.

One thing that is very easy to do in regular PHP programming is setting a session variable. All you really have to do is set the variable in $_SESSION and you are good to go. In Magento, you probably could do it this way, but you would probably get this feeling that you are doing it incorrectly (and you would be correct).

Luckily, setting session variables in Magento is only difficult until you see it once, and then it is just as easy as setting the variable in $_SESSION. As long as you know how to set variables on an object, you can set a session variable. Look at the following code:


This piece of code sets the session variable my_cool_session_value to the value of “variable”. Getting the value back out, all you have to do is replace “set” with “get” and it will return the value.

Magento Debugging Basics

Magento is a big system. If you are developing for Magento it is inevitable that you are going to either need to trace down a big or just figure out how a particular process works.

The best thing to do is to start with the controller that is triggered when the process starts. If you are not able to figure out which controller you are starting from, I suggest you buy Commerce Bug by Alan Storm. It will take all the guess work out of that for you as well as tell you a bunch of other information about the page you are currently viewing.

Now that you know where to start, lets talk about the functions and commands I find most useful when debugging Magento.

echo “captured”; exit(); – This does exactly what it looks like. Echos out the word “captured” and stops execution. This is helpful so that you can verify that the code you think is running, is in fact running. It is also a good to use in conjunction with the other commands so you can stop the process without loading the layout or template of the site.

echo get_class($obj); – This will simply tell you the name of the class that $obj is. Since class names in Magneto (and the Zend Framework for that matter) tell you where the actual file is located, this is very helpful so you can follow the next step of the code.

print_r(get_class_methods($obj)); – get_class_methods returns a list of explicitly defines methods that $obj currently has. I say explicitly defines because it does not display functions that come from Magento’s magic functions (all the nice getters and setters).

debug_stacktrace() – This function is good when you know the end point of the code you want to debug but want to see where it was called from. This displays a complete stack trace of the code from the point this function is called.

print_r($obj->debug()); – Nearly every single object in Magento extends Varien_Object. One of the methods that Varien_Object has is debug. This function will show you the data that this object currently holds.

Those are the very basics, but you can trace Magento code very easily with these few functions. What other functions do you use to debug Magento?

Have Your Magento Caches Update Themselves

Magento has a lot of caches. They are (in my opinion) the biggest reason Magento is usable as a platform (If you think Magento runs slowly now – turn them off for a little bit).

One thing that I as a programmer find odd is that the caches in Magento are intelligent enough to flag themselves as invalidated, however they generally require that they be refreshed by hand. This can be especially irritating when you are running Magento Enterprise Edition and your full page cache is constantly being invalidated due to product and category updates.

In order to improve our site performance I wanted to find a practical way to run with the full page cache on all the time without requiring me to babysit it 24 hours a day. I figured I had to find the code that was triggered when you told the admin panel to update the cache.

It turns out that like most things in Magento, unless you know how it works, it is not immediately obvious where this code is located. One tool I have found invaluable is Commerce Bug by Alan Storm. This tool told me that the cache admin page is controller by the controller that is located at:


Now in this controller you will find a number of actions. The one that is going to help us is massRefreshAction(). Inside you will see that there is code that actually refreshes the cache

$tags = Mage::app()->getCacheInstance()->cleanType($type);

This is close but not quite what we need yet. The $type is a string code for the cache. We don’t want to always refresh the cache. Just the ones that have been flagged as invalidated.

Looking deeper into the ->getCacheInstance() class that is returned shows us an interesting function that is available called ->getInvalidatedTypes(). BINGO! That is exactly what we are looking for.

Looking at what this function returns we find an array of objects that contain the codes of caches that have been invalidated. Now all we have to do is iterate through this list and refresh those caches.

The final script will look like the following:

$types = Mage::app()->getCacheInstance()->getInvalidatedTypes();
foreach($types as $type) {

Now that we have a script that is refreshing the caches, we just need this script to run every so often and it will refresh any caches as required. I set it to run every 2 minutes, but your mileage may vary.

Make A Custom Function Available In The Entire Magento System

One of my co-workers recently started working with Magento. Until recently he was primarily working in a custom system we had developed.  One of the functions that he was very used to using was a debug function that simply was a wrapper for PHP’s print_r() that echoed out the beginning and ending pre tags.

Now this was not a show stopped for him, but it quickly became irritating for him to not have quick function available to him in Magento (especially since Magento has some massive objects) and he forgot to put in his pre tags.

Since I am a nice guy, I decided to see if there was a way that I could bring this little function into the system for him and it was easier than I thought it would have been.

In order to add a function that is available in every part of the Magento system you have to remember how a request flows through Magento. Everything starts in the index.php file. All I had to do was add this function to this file and it was available everywhere.

Now a few things to consider when doing this.

  • I would not do this in production (it probably would not hurt in this case, but you never know)
  • In terms of Magento coding standards, I would call this a little “dirty” the more “correct” way to do this would be to put this code somewhere in a header in a module.

If you are curious what the actual function looked like I have posted it below:

function print_array($var, $echo=false) {
  echo "<pre>";
  $str = print_r($var, $echo)
  echo "</pre>";
  return $str;

So there you have it. A quick and dirty way to bring in your own functions to the entire Magento system.

An Overview of Magento’s Get and Set Methods

Magento handles its get and set methods in a way that if you do not understand how it works it can be confusing to you. In the beginning of this article you have to take a leap of faith and believe in magic.

In Magento you can take nearly any model and get all the information about it with a simple function call. See the example below:

$product = Mage::getModel('catalog/product')->load(1500);

This code will return an array of all the basic information about the product. For this example lets say that it only returned two elements to the array “name” and “meta_description”.

Now in order to get this information you will have to take the information and camel case it to create the function. So to get the information you would write the following:

echo $product->getName();
echo $product->getMetaDescription();

Do you see how the Meta Description function was formatted? The first letter of the words are capitalized (or camelized) to create the function. So lets say you had an attribute called this_really_important_long_attribute you would call $product->getThisReallyImportantLongAttribute()

Now that you understand that, in order to set the attributes value, you simply replace “get” with “set” and pass the variable as a parameter of the function. So to set the name you would make the following function call:


Ok remember when I said that you had to believe in magic? That is because if you look at the Product model, you will not find these functions defined anywhere. In fact if you are hardcore you can follow the class all the way to the top and you will not find these functions defined.

Ok now that you believe in magic, let’s take the curtain away and show you how Magneto accomplishes this. Nearly every class in Magento extends from the Varien Object (which is located in the /lib/Varien/Object.php file). You will see there is a getData() and setData() functions. These look like they could do the actual setting and getting but this is not the magic we are looking for.

Farther down in the file you are going to find the __call() function. This is the magic. This magic here is actually from PHP. The __call() function gets called anytime you call a function on a class that does not exist. The __call() function takes two parameters. The first one is the name of function that was called, the second one is the data that was passed to the function.

Now what Magento does is take the function that was called, determine if the function is a get or set function. Then it parses the string to find the attribute and then it makes the appropriate function call to get or set the data.

Once you see how this works you can see how awesome this functionality actually is.

Hosts File Editor 1.5 Released

There were a few things about the Hosts File Editor that I thought needed to be done so I spent some time this afternoon to do them. You can now have the program automatically organize the hosts file by IP address (then it sorts the domains by name). You can also edit entries now (before you had to delete and recreate the entry).

Go to the software page to download it now.

Get Your Magento System’s Time

Magento handles time in a pretty different way. Instead of just using the time on the server it automatically converts the time to the selected time zone in Magento’s system.

The way to get the current time is by using the following code:


What this will do is take the timestamp that you get from the time() function and converts it to the timestamp that Magento says what time it is. So you can wrap this function into PHP standard date() function to output in a format you are used to.

Using RedirectMatch to Cut Down on Number of Redirects

Last year I had a project that required me to redirect over 50,000 URLs from an old website to a new website. This was one heck of a project, but having all those links disappear from Google simple was not an option (the company relies pretty heavily on Google for their revenue).

One thing that I noticed was that on the old website, a page could have multiple URLs. Some pages had 2 URL’s but some had up to 7 or 8. This prospect meant that I was going to have to create well over 100,000 redirects in my .htaccess file. Luckily the URLs, while they were different, they had a matching pattern to them.

The URLs looked something like this:

You will notice that these URLs all have the number 11023 in the exact same spot in the URL while just about any other thing about the URL is different. Now usually I would have written three 301 redirects for these that would have looked something like this:

redirect 301 /products/23/46/11023/the-first-product-name.html
redirect 301 /products/22/46/11023/the-first-product-renamed.html
redirect 301 /products/22/56/11023/i-changed-this-product-name-yet-again.html

This isn’t bad when you have only a few URL’s, but remember we have 50,000 more of these. We are also trying to make sure that we cover the highest amount of URLs possible (we are trying to make sure the company does not fall out of favor with Google) so we really should handle ALL possible situations. What we can use is a something called RedirectMatch. It gives you the ability to use regular expressions in your 301 redirect entries. So now we can create a single line that looks like this:

RedirectMatch 301 /products/(.*)/(.*)/11023/(.*)\.html

Now all three listed old URLs will redirect to the proper new page, as will any other URL that comes to the website that matches this pattern. Now one downside to using this method is that this takes up more time for Apache to check the incoming URL to find a redirect. You will notice that all these URLs were in a products directory. So what we can do is put all these redirects inside an .htaccess file in the products directory on the web server so only requests that are referencing the products will have this small lag.