Magento Design Patterns – Part 2: Front Controller

Magento uses the Front Controller pattern to implement workflows for it's application.  It has a single entry point (index.php) for all of it's requests.  Let's see how it all works.

Magento leverages the class Mage_Core_Controller_Front_Action.  A module's controllers usually extend this base class.

Magento handles requests through URLS in the browser.  The front controller helps to process these requests.

A url is broken up into multiple sections.  A basic url has the following elements:

  • A router
  • A controller
  • An action

A router is defined in your Magento module configuration xml.  This is an alias for your module.  It is the first section after your base URL.

A controller is a class used to help process your request.  It is the second section after your base URL.

An action is the actual method called within your defined class.  It is the third section after your base URL.

Here is a basic example of Magento's Front Controller process.

http://www.mymagentosite.com/customer/account/login/

http://www.mymagentosite.com/ - Base URL

/customer/ - Router for the Customer module

/account/ - Account controller class.  This is located in the controllers folder of the Customer module and is the file AccountController.php and calls the class Mage_Customer_AccountController.

/login/ - The actual method called within Mage_Customer_AccountController.  Whenever a method is called, standard Magento practice is to append the word 'Action' at the end, to differentiate between methods that parse files.  The method called here is loginAction().

Anything after the standard router/controller/method call is parsed any additional parameters are parsed as key=>value pairs to be handled with the request.  For exaample:

http://www.mymagentosite.com/sales/order/view/order_id/24/

This request would load the Sales module through the router, load the Order Controller and call the method viewAction().  It then passes the key/value pair of order_id=>24.  You can fetch this value from calling the following within the controller:

 
// $order_id = 24;
$order_id = $this->getRequest()->getParam('order_id');
 

But what happens when you only see a url like this?

http://www.mymagentosite.com/customer/

The other parts are missing! Whenever there are no other parts of a URL request, they are automatically filled in with an index parameter. So for this example,

http://www.mymagentosite.com/customer/

is the same as

http://www.mymagentosite.com/customer/index/index/

Which will pull the customer router from the module, load IndexController.php and call indexAction().

References for Front Controller:
http://en.wikipedia.org/wiki/Front_Controller_pattern

Posted in Magento | Leave a comment

Magento Design Patterns – Part 1: MVC


Magento utilizes a unique MVC pattern, utilizing a DOM based configuration layer.  It leverages xml to drive the configuration and actions of the application on top of the regular Model-View-Controller architecture.

Models

Magento utilizes Models to leverage the business logic of the application.  It also leverages resource models for database interaction.  You can leverage Mage_Core_Model_Abstract to see how Models are built. Models are held in the Model folder of a particular Module.

Views

Magento uses fat views to help display it's content.  It leverages classes called Blocks to help in the rendering of it's views.  Every view has an appropriate class to correspond with it.  Views are held in theme files.  Mage_Core_Block_Template will get you started.  Views are held in the templates located in app/design/ and Blocks are held in the Block folder of a particular module.

Controllers

Magento uses thin controllers for it's process.  It utilizes controllers mostly for driving the applications requests.  It helps load the module, the controller, and the method.  Blocks/Views take care of much of the rest. Mage_Core_Controller_Front_Action will get you started.  Controllers are stored in the controllers folder of a particular module.

References for MVC:

http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Posted in Magento | Leave a comment

Magento Certification Review

I just took the Magento certification exam at Magento Imagine today.  I am proud to say that I passed.  It was not easy however.  If you are looking to take the test, here are a few quick tips to help you:

  1. Know the layout XML for Modules thoroughly
  2. Know the EAV module thoroughly
  3. Know Quote, Payment, and Order Classes and how they are utilized
  4. Know how to create admin interfaces and what classes help in this process.

Obviously, you should know this stuff as well as everything else they recommend in the study guide, but it's these things that they a) delve into deeper than I had thought, and b) they cover many things that are not covered in the Fundamentals of Magento Development course.  I highly recommend you have been developing modules solidly in Magento for at least a year.

Also, beware of trick questions.  Sometimes, they will throw you for a loop for items that are close, but not quite right.

Bottom line, know your stuff, study hard, and make sure you focus on Module development.

Look for that great badge on my site very soon!

Posted in Magento | Leave a comment

Magento Imagine Conference 2012 Day 2

Magento Imagine's opening keynote was good and bad.  Some good news about Magento and Magento 2.  And some very bad news about Magento 2.

Magento Community 1.7 and Enterprise 1.12 were released today.  This gives us some great updates like:

  • different base pricing for customer groups
  • Automatic generation of multiple coupon codes
  • Backup and rollback functionality
  • EU compliance
  • REST API

Enterprise gives us customer and visitor segmentation and mobile HTML 5 capabilities.

The next bits were around Magento 2.  Magento 2's focus is on refactoring, modularity, and simplified customization. Magento 2 will now utilize jQuery.  It also has some amazing drag and drop theme update abilities.  This functionality is very unheard of currently in the marketplace.  It will be a great feature for Magento users.

That brings us to the bad news.  They announced today that Magento 2 will be postponed until the first half of 2013.  We used to have 1st quarter '12 estimates, then 3rd quarter.  Now we are all the way into next year.  That's pretty brutal.

Otherwise, Imagine's been great so far!  Hope to see some more great stuff tomorrow!

Posted in Magento | Leave a comment

Magento Imagine Conference 2012 Day 1: Bar Camp

If anyone was there, they will definitely tell you, it was a whirlwind. It was information overload and you didn't know what to choose. Should you go with Beer or Liquor at the bar, but you don't want to waste your two free drink tickets. Just kidding ;) (but not really).

The sessions were great. The only problem. Fast. Very fast. Almost too fast. They wanted to cram a lot into the bar camp and they did a phenomenal job. There were six areas each running a total of six sessions a piece.

For what I actually got to attend, here are the good parts:

1.7 is coming, and you can say goodbye to slow API calls. They have now integrated RESTful services. Yay! (Yes, the all-numerical sku bug is still there...sigh).

Magento 2 themes utilize a fallback structure that allows us to keep our modules entirely outside of the theme and skin folders. Welcome to TRULY modular, well, modules.

The test automation framework is amazing. With just 4 lines of code, you can deploy and run an entire test.  It keeps business logic, Data, and UI separate, providing a solid structure in which to test your framework.  You can run entire tests, smoke tests, load tests, and Unit tests with the framework.  Oh yea, it's also free and available now.

Moving your magento modules to Magento 2 will not be as big of a pain with the TAF (Test Automation Framework). You can run a legacy check and allow for it to catch any problems against the new version.

Roy Rubin was there, (that's just cool in general).

Magento Community 1.7/Enterprise 1.12 is released tomorrow (Tuesday).

One more thing.  I want to start trending the hash tag #HeardItFromAnOrangeShirt, so use it whenever you hear a good piece of Magento info not in the presentations.  If you heard it from a Magento employee, post it so everyone knows!

My company, Crown, will be there at the marketplace tomorrow showing off our latest analytics offering.  We also have a cocktail party with Exact Target tomorrow so stop on by and grab some invites.  We are raffling off a TV, bose stereo system, and iTunes Gift Cards.

Posted in Magento | Leave a comment

The Magento index.php File

With everything that Magento does, it's index file seems remarkably short. It merely serves as the entry point in it's Front Controller pattern. So let's breakdown what Magento does when you load up a page.

The first thing it does is makes sure that you are running the least compatible version of php, 5.2.0. If not, she throws an error message and quits.

 
if (version_compare(phpversion(), '5.2.0', '< ')===true) {
    echo  '
<div style="font:12px/1.35em arial, helvetica, sans-serif;">
<div style="margin:0 0 25px 0; border-bottom:1px solid #ccc;">
<h3 style="margin:0; font-size:1.7em; font-weight:normal; text-transform:none; text-align:left; color:#2f2f2f;">
   Whoops, it looks like you have an invalid PHP version.
  </h3>
</div>
 
Magento supports PHP 5.2.0 or newer. <a href="http://www.magentocommerce.com/install" target="">Find out</a> how to install Magento using PHP-CGI as a work-around.
 
         ';
    exit;
}
 

Next, she sets the error reporting level.

 
/**
 * Error reporting
 */
error_reporting(E_ALL | E_STRICT);
 

Next, she looks to see if compilations are enabled by checking for the config.php file located in the includes/ folder.

 
/**
 * Compilation includes configuration file
 */
$compilerConfig = 'includes/config.php';
if (file_exists($compilerConfig)) {
    include $compilerConfig;
}
 

Next, she checks to see if Magento is installed by checking for the Mage.php file located in the app/ folder. If not, she exits.

 
$mageFilename = 'app/Mage.php';
$maintenanceFile = 'maintenance.flag';
 
if (!file_exists($mageFilename)) {
    if (is_dir('downloader')) {
        header("Location: downloader");
    } else {
        echo $mageFilename." was not found";
    }
    exit;
}
 

After that, she checks to see if the maintenance flag is set by looking for the maintenance.flag file inside the app root. If it is found, she exits once again.

 
if (file_exists($maintenanceFile)) {
    include_once dirname(__FILE__) . '/errors/503.php';
    exit;
}
 

If it passes all those checks, it includes the app/Mage.php file.

 
require_once $mageFilename;
 

Next, it checks the server to see if developer mode is enabled. (This can be set in your apache .htaccess file or php.ini file).

 
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    Mage::setIsDeveloperMode(true);
}
 

After that, it resets the umask. Read more about that here.

 
umask(0);
 

Lastly, it checks for store codes via the server, and runs the Magento application via Mage::run().

 
/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';
 
/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';
 
Mage::run($mageRunCode, $mageRunType);
 

That's it! In roughly 50 lines and some comments, Magento starts up and runs. Obviously it's simply only the entry point of a complex network of includes, abstracts, inheritance, and magic methods and files hidden deep within the caverns of Magento. You still have to admire the beautiful simplicity of the Magento index file.

Until Next Time...

Posted in Magento | Leave a comment

Turn On Maintenance Mode in Magento

A quick and easy way to turn on maintenance mode inside of Magento is to create a file called maintenance.flag and put it in your application root folder. This way in case you need to upgrade your system, perform maintenace, or otherwise take your site offline, you simply drop this file and you are set to go! When you want to bring things back up again, simply delete the file. The file doesn't have to have anything in it, but I would put a date in there and the reason for taking it offline, just in case.

Posted in Magento | Leave a comment

Magento Compilation Process

So what is the Magento compilation process?  The short description would be, "An easy way to improve Magento performance."  That is true.  But what does it do exactly?

Whenever Magento tries to load a class, it goes through the autoload process.  This basically means it splits up the class name, creates and sets an include path, and locates the class from there.  That's all good and fine, but when it does this quite a few times per page load, it gets a little cumbersome to go through the entire directory structure.

In order to combat this performance bottleneck, Magento uses a compiler process.  What it does, is essentially takes all the classes, and places them in a single location instead of running through the entire process of loading a single class.  It makes loading times much more quick.

Whenever you turn on compilations, it places all files inside your /includes/src/ folder.  It also renames all files to the full class name to make sure it is unique and no duplicates are accidentally loaded.
Continue reading

Posted in Magento | Leave a comment

Varien Profiler for Magento

Do you have slow page load times? Are you developing a plugin and suddenly it's making your site run VERY slow?

In order to address performance issues within your code, you can use an out of the box solution provided by Magento. It is the Varien Profiler. It basically monitors the time and memory allocation of your application loading cycle at specific intervals you set. It's also very easy to use.
Continue reading

Posted in Magento | 2 Comments

Class Errors with Meta Boxes in WordPress

I ran into an issue while creating a recent plugin for WordPress.  It had to do with meta boxes.  I was trying to add a meta box and the hook was registering, but unfortunately, when it came time to call the hook, it was saying that the method didn't exist.  Somewhere between registration and render the class had disappeared.

What was going on?

After a little head scratching and a little digging, I found out about a scope issue when it came to the post page.  If you are rendering meta boxes, make sure that the scope is correct with your meta box.  Don't call your hooks outside of the class that renders the box.  Keep it inside the class itself and pass the class by reference.
Continue reading

Posted in WordPress | Leave a comment