Creating a Magento Script that Disables Coupons

As I mentioned in my previous post, I had to quickly find a way to disable a large number of coupons in Magento.

Generally I would say that it would be faster to do this by hand in the admin panel, but I had to disable 62 of them (and I was not sure that the solution would work so I did not want to put all that time into it only to not have it work). Continue reading Creating a Magento Script that Disables Coupons

One Way To Fix Add to Cart Being Slow In Magento

Please Note: This post is more of an anecdotal post as opposed to a tutorial. There are no code samples and the actual code that I discuss may not be 100% accurate as I am typing this at the end of a 12 hour work day. I wanted to get this story out so if there are people out there with a similar problem, they can solve it quickly. Continue reading One Way To Fix Add to Cart Being Slow In Magento

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:

Mage::getSingleton(‘customer/session’)->setMyCoolSessionValue(“variable”);

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:

/app/code/core/Mage/Adminhtml/controllers/CacheController.php

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) {
     Mage::app()->getCacheInstance()->cleanType($type->getId());
}

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);
print_r($product->debug());

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:

$product->setName($new_name);

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.

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:

Mage::getModel('core/date')->timestamp(time());

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.