Google
 

Wednesday, June 17, 2009

Overriding Controllers and Actions in Magento

In my previous post, I had explained a way to add extra controllers to existing route. Here I am going to explain another method which is used for overriding controllers and actions. Like my each post on tips & tricks, I am going to first explain where the trick is applicable! I am considering that readers of this post are aware of MVC architecture in Magento.

Let me explain the difference between the both tricks. The trick explained in previous post is used when we need additional URLs in same route i.e. additional controllers and actions. I have already explained an example there. Here we need to change the behavior of existing controller and action. For example, when a customer adds a product to shopping cart, addAction of CartController of Mage_Checkout module is called. If we want to override this by My_Checkout, MycartController, myaddAction as similarly as we can override Models and Blocks in our own modules. So the the trick in previous post is used for overloading while the trick here is used for overriding.

Of course, this too can be done just by simple XML configuration (apart from creating custom controllers and actions) but without using route rewriting approach! Let's take a same example above where we want to override action for checkout/cart/add. First create My_Checkout module with MycartController class and myaddAction method defined within it. The way to do this is better explained in this wiki. Then the configuration required in etc/config.xml of My_Checkout module is like below:
<global>
  <routers>
    <checkout> <!-- Mage_Checkout module -->
      <rewrite>
        <cart> <!-- CartController -->
          <to>mycheckout/mycart</to> <!-- My_Checkout module, MycartController -->
          <override_actions>true</override_actions>
          <actions>
            <add> <!-- addAction -->
              <to>mycheckout/mycart/myadd<to> <!-- My_Checkout/MycartController/myaddAction -->
            </add>
          </actions>
        </cart>
      </rewrite>
    </checkout>
  </routers>
</global>
Here we also need configuration to define module front name for My_Checkout module as below:
<frontend>   <!-- It will be admin for overriding admin controller -->
  <routers>
    <mycheckout>
      <use>admin</use>
      <args>
        <module>My_Checkout</module>
        <frontName>mycheckout</frontName>
      </args>
    </mycheckout>
  </routers>
</frontend>   <!-- It will be admin for overriding admin controller -->
Note: The above configuration examples only display portions of config.xml file. Please do not consider it as a complete configuration.

Simple isn't it? Now let's understand how it works. The work flow of this rewrite process is little bit tricky.
  1. When an checkout/cart/add action is going to be dispatched, first it is passed through rewrite process.
  2. Rewrite process tries to find global/routers/checkout/rewrite/cart node is found in configuration, where checkout is front name of Mage_Checkout module and cart indicates Mage_Checkout_CartController.
  3. If this node is not found, rewrite process is not be continued and returned to dispatch process. So the action is executed normally. Otherwise, rewrite process is continued.
  4. Now, under this node, it tries to find whether override_actions node is true or false. By default value of override_actions is true. So if it is not added in configuration, it is considered as true.
  5. If override_actions is true, it overrides all actions of Mage_Checkout_CartController with same actions of My_Checkout_MycartController as defined by to node value mycheckout/mycart. For example, if we have defined addAction and indexAction methods inside My_Checkout_MycartController, then it automatically overrides both addAction and indexAction of Mage_Checkout_CartController. In short using to node and override_actions node we can override whole controller instead of individual actions.
  6. If actions/add node is defined where, add indicates addAction of Mage_Checkout_CartController, then override_actions node value is not considered and overrides action by value of actions/add/to node which is mycheckout/mycart/myadd i.e. My_Checkout module, My_Checkout_Mycontroller and myaddAction. So we can also override individual actions by this type of configuration.
Sounds good again? Try it too...

Thursday, April 02, 2009

Secret feature of Magento 1.3: Sharing same route name for different modules!

I have already talked about flexible architecture of Magento Commerce in my previous posts. As Magento allows to customize its default behavior without touching and modifying the existing code, we can override any of the existing class by defining our own in our out of the box extensions. I have also played with Magento by creating variety of extensions, and believe me, it was a real fun of programming. Magento allowed me to change everything I desired.

But I was still feeling that something is missing! And that missing thing was provision for sharing of route names which is now available since Magento 1.3 released yesterday. Now, the first question may arise here that "what is sharing of route names?". 'Sharing of route names' is not a functional feature. So if you'll try to find it in Magento features list, you may be disappointed. Actually it is a feature for developers. It is not even mentioned in Magento 1.3 Release Notes. I found this secret feature in newer version of Magento when I was roaming inside the code to search the difference between 1.2 and 1.3. Let me explain this feature in more detail.

Sometimes, I was supposed to develop extensions which required extra pages or forms in existing modules. For example, adding extra features to Admin Panel. I needed some extra controllers and actions for Admin Panel. This seems OK. I could easily create a local module for it as explained in this Wiki. But an uncomfortable part in this way is this configuration:
<admin>
 <routers>
   <sintax>
     <use>admin</use>
     <args>
       <module>Mage_Sintax</module>
       <frontName>sintax</frontName>
     </args>
   </sintax>
 </routers>
</admin>

Here, all URLs of my additional pages will be started by /sintax/ while all other admin panel pages will be started by /admin/. I am forced to use other routes for my additional modules. I cannot just add more URLs to 'admin' route! This can be fare for Admin Panel pages as they will never be visible by public. But what if I want to add more pages to frontend? If I add any extra page to 'catalog' module, I can't define URLs for my pages starting with /catalog/. I have to define a route something like /mycatalog/ which I don't like!

One solution for this to use URL rewrite from /catalog/mypage/ to /mycatalog/mypage/. But unfortunately, URL helpers will still generate URLs like /mycatalog/mypage/.

The problem with the older version of Magento was mapping one to one relationthip with module front name to module real name i.e. 'catalog' => 'Mage_Catalog', 'admin' => 'Mage_Adminhtml' etc. So I could not map my additional module to existing front name. But Magento 1.3 allows to map additional modules to existing front names. How? Just by changing router configuration for module shown above to the following:
<admin>
 <routers>
   <adminhtml>
     <args>
       <modules>
         <sintax before="Mage_Adminhtml">Mage_Sintax</sintax>
       </modules>
     </args>
   </adminhtml>
 </routers>
</admin>
This configutation will add Mage_Sintax module to admin frontname. An attribute before can be added to give more priority then existing module in finding controllers. For example in this case, /admin/catalog/ URL will call a controller class Mage_Sintax_CatalogController, if it is defined and if not then it will call Mage_Adminhtml_CatalogController. Similarly, after attribute will assign less priority then the existing module. We can add as many modules as we need to the same front name using this way.

Sounds good? Then try it yourself...!

Tuesday, November 18, 2008

Zend Framework 1.7 with AMF support released!!!

Zend Framework 1.7.0 is now available from the Zend Framework download site: http://framework.zend.com/download/latest

This release introduces many new components and features, including:

  • Zend_Amf with support for AMF0 and AMF3 protocols
  • Dojo Toolkit 1.2.1
  • Support for dijit editor available in the Dojo Toolkit
  • Zend_Service_Twitter
  • ZendX_JQuery in extras library
  • Metadata API in Zend_Cache
  • Google book search API in Zend_Gdata
  • Preliminary support for GData Protocol v2 in Zend_Gdata
  • Support for skip data processing in Zend_Search_Lucene
  • Support for Open Office XML documents in Zend_Search_Lucene indexer
  • Performance enhancements in Zend_Loader, Zend_Controller, and server components
  • Zend_Mail_Storage_Writable_Maildir enhancements for mail delivery
  • Zend_Tool in incubator
  • Zend_Text_Table for formatting table using characters
  • Zend_ProgressBar
  • Zend_Config_Writer
  • ZendX_Console_Unix_Process in the extras library
  • Zend_Db_Table_Select support for Zend_Paginator
  • Global parameters for routes
  • Using Chain-Routes for Hostname-Routes via Zend_Config
  • I18N improvements
    • Application wide locale for all classes
    • Data retrieving methods are now static
    • Additional cache handling methods in all I18N classes
    • Zend_Translate API simplified
  • File transfer enhancements
    • Support for file elements in subforms
    • Support for multifile elements
    • Support for MAX_FILES_SIZE in form
    • Support for breaking validation chain
    • Support for translation of failure ,messages
    • New IsCompressed, IsImage, ExcludeMimeType, ExcludeExtension validators
    • Support for FileInfo extension in MimeType validator
  • Zend_Db_Table_Select adapater for Zend_Paginator
  • Support for custom adapters in Zend_Paginator
  • More flexible handling of complex types in Zend_Soap

In addition, almost three hundred bugs have been fixed:

http://framework.zend.com/issues/secure/IssueNavigator.jspa?requestId=10903

Wednesday, September 03, 2008

Zend Framework 1.6 Released!!!

I develop my PHP web applications in Zend Framework since its first stable release. I compared it with many other frameworks and I choose Zend Framework for my development approch because of its outstanding flexibility, huge community support and transperent development roadmap.

Yesterday, Zend has released a brand new version of Zend Framework 1.6. This new version has introduced many new useful features. The new 1.6 version includes built in support of Dojo Toolkit, a powerful AJAX and UI library as well as PHPUnit, the most powerful Unit Testing framework for PHP.

The complete list of new features of Zend Framework is:
  • Dojo Integration
    • JSON-RPC
    • Dojo Data packing
    • Dojo View Helper
    • Dijit integration with Zend_Form & Zend_View
    • Dojo Library Distribution
  • SOAP
    • SOAP Server
    • SOAP Client
    • Autodiscovery
    • WSDL access
    • WSDL Generation
  • Preview of Tooling Project in Laboratory (see /laboratory folder)
    • Command Line Interface
    • Project Asset Management
  • Unit Testing Harness for Controllers
  • Lucene 2.3 Index File Format Support
  • Zend_Session save handler for Database Tables
  • Paginator Component
  • Text/Figlet Support
  • ReCaptcha Service
  • Zend_Config_Xml Attribute Support
  • Character Set Option for DB Adapters
  • Zend File Transfer Component
  • New Media View Helpers (Flash, Quicktime, Object, and Page)
  • Support in Zend_Translate for INI File Format
  • Zend_Tool
  • Zend_Wildfire Component with FireBug Log Writer
  • Zend_Db_Profiler with FireBug support
With the lots of new features, Zend Framework has also enhansed the performance compared to older releases. You can download the latest release of Zend Framework from here.

Zend Framework has made its own place in the clouds of more than 40 PHP Frameworks.Technorati Tags: , , ,

Friday, August 22, 2008

Introducing Web Magician Toolbar

New Web Magician Toolbar is now available. You may really like to try our new toolbar because it's free, private and secure. It takes few seconds for installation. It also includes the features which may make your browsing and searching easier and keep you connected with us:
  1. Accelerated search bar - Google powered search bar for faster and accurate search results
  2. E Mail Notifications - Get new email notifications for your Yahoo, Gmail, Hotmail or POP3 Mails
  3. Radio - Stay tuned and listen each Web Magician blog entries as Podcast
  4. RSS feeds - Get updated with latest posts of Web Magician
  5. Pop-up Blocker - Block annoying pop-ups automatically
  6. Privacy - Clean your private data like cookies, history, cache from your browser
  7. Weather forecast - Get world wide weather information
  8. Web Magician Quick launch button - Visit us on a single click
Web Magician Toolbar is available for Mozilla Firefox and Internet Explorer. Try Our Toolbar


Sunday, August 10, 2008

Actual Model implementation in MVC Architecture

Frameworks like Ruby on Rails have made MVC (Model View Controller) architecture more popular and easier. Most of the PHP frameworks like CakePHP, Symfony, PHP on Trax, Zend Framework have followed similar patterns as Ruby on Rails for MVC. By using these frameworks, MVC in design is no longer painful.

But do all people maintain MVC in real manner??? The major misconception the people have is about the role of Model in MVC. I read many tutorials of Ruby on Rails, Zend Framework, CakePHP and Symfony. Many of the tutorials explain the role of Model as to access data from database. That means Model would be responsible for providing and updating of data into the database!!! All the business logic would be handled by the Controller!!!

It is a simple way, but would be fare only for small scale applications which do only CRUD (Create, Read, Update, Delete) operations. Then, what about large applications where business logic is much complex? Is it a good idea to encapsulate all business logic in Controller?

I recently read some blog posts such as:
ActiveRecord sucks by Kore Nordmann,
ActiveRecord sucks, but Kore Nordmann is wrong by Mike Seth,
ActiveRecord does not suck by Bill Karwin and
Fat Models and the Data Access Layer by Dave Marshall

Bill Karwin and Dave Marshall explains actual implimentation of Model. The Model is a business logic of your application not only the database access layer. Active Record (in RoR, Cake, Symfony) or Table/Row Data Gateway (in Zend Framework) should be used as a part of model not as a model. Your all business logic should be encapsulated in Models only.

One of the strongest reasons for following MVC is reusability. Think about the case when you want to port your PHP web application to desktop application using PHP-GTK. If you have followed correct MVC architecture then you can easily reuse the same Models of web based application into GTK based application. If you have encapsulated your business logic in controller, then you have to rewrite all the code again for GTK!!! It would simply kill DRY (Don't Repeat Yourself) principle!!!

I am using Zend Framework since its 1.0 release. At the beginning I read lots of tutorials about it and I was in the same misconceptions about the Models. Then I had taken a look around the code base of Magento Commerce. As I told in my previous post, Magento is built on Zend Framework and follows MVC architecture. (I noticed that Magento uses many ZF components but does not use Zend_Controller and Zend_View for its MVC because of its own custom patterns. But the implementation is quite similar to Zend Framework.) I'd noticed that MVC is followed in really nice way and provides very much flexibility for customization. It is very good example for enterprise application design.

Tuesday, April 01, 2008

Magento 1.0 has arrived!!!

My previous post was published before the launch of Magento - Preview Version and was introducing the features those were going to be implemented (and now have been implemented). The preview version was released on 31st August, 2007. So it has been very long time since my last post but busy schedule of life was'nt giving me a single moment for blogging.

And yesterday, on 31st March, 2008, long awaited Production version of Magento Commerce has been released.

Since the release of first preview version, the updates was being released frequently. With every release, Magento was shining more and more. The progress is incredible in very less time. Magento provides lot of exciting features like Multiple Stores and Websites, Google Checkout support, Single Page Checkout, Shipping to multiple addresses in one order and many more.

Varien - Magento Company has already announced parnership and collaboration with Parallels and Media Temple to deliver Magento 1.0 through a one-click installation wizard.

As a developer, the most impressive thing I found in magento is its flexibility for customization. As I have already mentioned in my previous post, magento is developed on Zend Framework and uses MVC architecture, which makes magento easier to maintain. Apart from that, magento also provides out of the box solution for customization. That means, magento can be customized as you need without modifying a single line of code in existing core modules. Instead, you can develop your own modules with specific configuration which overwrite the behavior of existing core modules. I love this way because it provides flexibility for upgrading magento to newer version.

So, on this occasion it really worths if they say:
Open Source eCommerce has officially evolved.