Friday

Writing a custom module in Magento

Time to move on to some more serious stuff concerning Magento. My last few posts were about understanding a way to use Magento functions. Functions like getModel, getData, getSingleton and so on. Most important it was a way of showing you how to find the available functions ascreend how to extract the data from objects. Not sure if I fully seceded in that but hopefully I helped a bit.

Before I start with the explanation on how to actually write a module let’s take a deeper look at the module philosophy. You can look at the module as your application (that’s the way I look at it) within the main application (Magento). Just for the consistency let’s stick to the module terminology. Each module is comprised of various parts working together for the common goal. If your module is named, let’s say, SomeCoolPaymentServiceModule then the common goal of the module parts is to achieve full integration (inner workings) of Magento system with the SomeCoolPaymentService service.

So what are the parts that make the module? In MVC architecture even the bare bone application is (mostly) written across three separate files. Model, View and Controller. Ideal case is the one where Model manages all of the database connections and queries, then passes the information to controller. Controller then reorders, maps, filters, does some logic on the data and passes it to the View. View is the thing we see. View is the file served to our browsers. In Magento case View is called Block. The same block whose name we see when we turn on System > Current Configuration Scope > Developer > Add Block Names to Hints to Enabled.

Magento is built on top of Zend framework. Since Zend is pure MVC framework so is Magento’s architecture MVC based. Open you Magento installation directory and drill down into the app/code/core/Mage/Catalog/ folder. Notice the word Catalog in this path? Well, the Catalog is one of the modules inside the Magento. And the app/code/core/Mage/ path is the path to all the Magento modules, the building blocks of Magento. Now that we know where to find modules, let’s look at the content of a module. This is the content of the Catalog module:

Block /
controller/
etc /
Helper /
Model /
sql /
Exception.php

As you might notice, there are more than three type of files here. By types I think of Model, View (Block), Controller. Magento’s structure is therefore more divided. We can see the Helper and sql folders as well. Although not every Model contains the same sub folder structure like this one you need to understand that this is somewhat of a blueprint of how Magento modules are built.

So how does one write a custom module? Presumption is that you already know how to create a custom theme. Across this walktrough I will be using paths showing mycustom as the name of my theme folder. Remember this so you don’t get confused. My module will be called ActiveCodeline (wonder why :) ).

Folder /app/code/core/Mage/ is used to store default Magento modules NOT the custom created ones. User (custom) modules are to be stored inside the app/code/local/ folder. The thing with PHP is that it lacks the support for namespaces. However, this did not stop Magento guys and girls for creating them. In the default Magento module folder /app/code/core/Mage/ word (folder) Mage is actually a namespace. Why is this important? Well, as I sad I’ll create a module named ActiveCodeline. Creating a directory app/code/local/ActiveCodeline/ simply means I created a new namespace named ActiveCodeline inside the user module folder. Therefore you should look at the ActiveCodeline folder as the namespace name not the module name for now.

Under the /app/code/local/ActiveCodeline/ folder (or shall I say under the namespace ActiveCodeline) create a folder (module) named Example like

app/code/local/ActiveCodeline/Example/

Now if we were to look at the newly created folder we should look at it the same way we look at the app/code/core/Mage/Catalog/ folder. Example (in our case) and Catalog (in Magento default case) are both modules. Now we can say Example is our custom module. This however is a bit contradictory since we are most likely to say that ActiveCodeline is the name of our module. What’s important is that you know the difference and avoid getting confused by the naming.

Now, let’s go into the /app/code/local/ActiveCodeline/Example/ folder (module) and create two subfolders there, Block and etc. Our folder structure should now look like

/app/code/local/ActiveCodeline/Example/
Block/
etc/

So far, we haven’t done anything that would make Magento see our new module. In order to get our module seen by Magento we need to register it. How do we register our module in Magento? drill down into the newly created

/app/code/local/ActiveCodeline/Example/etc/

folder and create config.xml file.

What do we write into this file? If you open up the app/code/core/Mage/Catalog/etc/config.xml file and have a look inside, you’ll see the stuff it contains. For our bare bone module we need to write the following into the config.xml file:



0.1.0




ActiveCodeline_Example_Block


After we save our config.xml file we can go to Magento admin, go to System > Configuration > Advanced. There you should see the ActiveCodeline_Example on the list among other modules.

Now we need to add some logic to our module. To keep things simple, I’ll make my module simply echo some stuff to the browser. Now lets create second file that we need to make our module work. Open up the app/code/local/ActiveCodeline/Example/Block/ folder and create a View.phtml file.

Place the following content into it:

class ActiveCodeline_Example_Block_View extends Mage_Core_Block_Template {

public function doSomeAction(){
$message = ‘

Hello from ActiveCodeline sample module…

’;
return $message;
}
}

Finaly, we go to our theme folder. As I told you at the beginning of this article, my theme folder is called mycustom. Therefore, inside the app/design/frontend/default/mycustom/template/ folder you need to create the example folder like

app/design/frontend/default/mycustom/template/example/

Now you create a file called view.phtml with the following content

/*
$this is now instance of ActiveCodeline_Example_Block_View
*/
?>

This is the output of the activecodeline example:

echo ‘Class name: ’. get_class($this) .’’;
echo $this->doSomeAction();
?>

Basically these three files conclude the creation of your bare bone module. To test if the module is working, go to Magento admin > CMS > Manage Pages > Home page then write the following somewhere on the page

Sample activecodeline message…


{{block type=”ActiveCodeline_Example/view” template=”example/view.phtml”}}

Notice the type=”ActiveCodeline_Example/view”. If you were to write it like type=”activecodeline_example/view” it wont work. Watch for the capital letters.

Now if you refresh the home page of Magento shop, you would see the result message of the new module.

As I said at the beginning, this is a bare bone module, dummy module or whatever you like to call it. My intention was show you how simple it is to create a basis for module. I haven’t mentioned sql folder here or helpers folder. I leave some things for you to do. Most of the tutorials out there on creating a custom module jump right into the fire going over trough stuff I intentionally left out but they leave the basis unmentioned. Then you end up with the tutorial on how to create something cool but you are missing few steps and you go crazy trying to figure out what’s missing.

If you truly understood this walktrough and my previous articles on Magento then you are ready to connect the dots and start making more serious modules.

courtsy: http://activecodeline.com

Tuesday

How to Import Products into Magento

There’s a little confusion among some on how to import products into a Magento ecommerce store. I spent some time today researching and trying to find the best method on doing this. The reason for my research is because there was no simple documentation anywhere that I could find on how to import products. Magento actually has built a pretty robust import/export mechanism into the ecommerce cms that has a ton of flexibility to do many things. I’m not going to cover all of those. This is just for those of you who simply just want to import products into their Magento cart.

Step 1 – Add a new product manually
add a new product manually to the catalog, assign it to a category, and fill out all fields that will be necessary to your store. The obvious ones are price, description, quantity etc. It’s important that you fill out all fields that you know you are going to need for all the products you import.

Step 2 – Export Your Products
Now we want to export your product to a .csv file so that we can view the fields that are required to import. Go to System >> Import/Export >> Profiles. Now click on Export All Products then Run Profile. Click on the “Run Profile in Popup” button. Once the export is completed, go to your var/export directory on your Magento install and you will find the .csv file there for you to download.

Step 3 – Analyze The .CSV File
Now if you look at your .csv export file you will see the field names that you need to match up. Now just start filling yours in and creating your csv file ready for import. This step is extremely important. Otherwise Magento cannot match what you are trying to import and the importing will fail. At a most basic level, here are the fields that I imported:

  • store
  • attribute_set
  • type
  • sku
  • category_ids
  • status
  • visibility
  • tax_class_id
  • weight
  • price
  • name
  • description

Step 4 – Import Your New .CSV File
Now go to System >> Import/Export >> Profiles. Now click on Import All Products. Change “Type” under Data Format to CSV/Tab Seperated. Now click on Upload File, and browse for your .csv file and click “Save and Continue Editing”. Now go to “Run Profile” and select your file from the dropdown menu. Click the button underneath to run the import. And whalllah. All your products should now be imported.

That was the easiest most simple approach that I could find for Importing Products into a Magento Open Source Ecommerce Store. Like I said I tried this myself and it worked well for me. After that, I went in and manually updated all of my Images and
Quantity numbers. You could even import those if you want to. But for
my purpose I didn’t need to.

courtsy: http://chasesagum.com

Monday

Web addresses to speak all languages

The Internet Corporation for Assigned Names and Numbers, or Icann, has set the ball rolling for web addresses in scripts other than Latin. This will allow uniform resource locators, as web addresses are called in virtual parlance, in languages other than English, including Hindi, Tamil or Bhojpuri.

About half of the world's 1.6 billion Internet users use languages based on scripts other than Latin and may cheer the move. India, which has 50 million Internet users, speaks hundreds of languages.

Icann, the non-profit group that oversees domain names, is meeting representatives from all over the world this week in Seoul to decide on this change, which will be one of the biggest in the 40 years of Internet. If it is cleared, Icann will begin accepting applications for non-Latin domain names and the first entries into the system are expected in the middle of next year.

Icann is also to decide whether it can give users freedom on global top-level domain names.

"If this happens, it will definitely increase the number of internet users. Why should users type in English if they could time in Tamil or Hindi," says Kiruba Shankar, founder chief executive officer of Business Blogging.

At present, web addresses are limited to 21 suffixes, such as, .com (80 per cent), .net and .info, and country-specific ones like .in for India. With this change, companies and individuals can have unlimited choices such as .indian, .delhi, .paris, .gabbarsingh or .whateveryouwant.

Corporate houses like the Tatas, Birlas or Reliance [ Get Quote ] could apply for .tata, .birla or .reliance and could, in turn, give each employee a .tata, .birla or .reliance email identity.

Like all good things, these will come at a price: Rs 40 lakh (Rs 4 million) to Rs 2 crore (Rs 20 million).

Jasjit Sawhney, managing director and chief executive officer of Net4India, an Internet service provider that offers domain registration services, says the move to open up web addresses is good "but will take time to trickle down in India because of technicalities".

Currently, names on the Internet can be typed in local scripts. For instance, you can type dukaan (shop) in Devnagari, the script for Hindi, but not .com.

Icann is in talks with information technology departments of countries to get the exact meaning of .com in local languages, say, Hindi or Tamil. "What do you call .com in Hindi? One has to decide on such issues," says Sawhney.

Naresh Ajwani, president-government affairs, Sify Technologies, who is attending the Icann meeting in Seoul, points out that the Department of Information Technology in India already has fonts for 22 local languages. "This, and the fact that GLTDs may be opened up to more domains, will witness a sea change in the way the Internet is structured," says Ajwani.

Leslie D Monte in New Delhi
Source:

Tuesday

Create a wordpress widget

This tutorial will explain how to create Wordpress widget from scratch. We will make widget using PHP5 OOP. You will also learn how to implement configuration page for your widget.

Getting started

You should already have Wordpress installed, either on your local machine or on a testing server. For this tutorial we will use the Wordpress version 2.7. You should also have a theme that support widgets. You could use the default one or make a wordpress theme from scratch and widgetize it.

Widget name

The first task in creating a Wordpress widget is to think about what the widget will do, and make a (hopefully unique) name for your widget. Check out Plugins and the other repositories it refers to, to verify that your name is unique; you might also do a Google search on your proposed name. The name can be multiple words.

Widget files

We will start by creating a folder widget-name in our wp-content/plugins/ directory, where Wordpress stores all it’s plugins. It’s a good idea to always create a folder for your plugin, even if it consists only of 1 file, so you could add more files later.

The next step is to create our main widget file widget-name.php. To make Wordpress recognize it as a plugin we should add a specific header to it, that describes our widget.

Widget header

php

/*
Plugin Name: Name Of The Plugin
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: A brief description of the Plugin.
Version: The Plugin's Version Number, e.g.: 1.0
Author: Name Of The Plugin Author
Author URI: http://URI_Of_The_Plugin_Author
*/

?>

Our widget should appear in Wordpress administration area in inactive plugin list. Information about your widget will be extracted from the header of a main widget file. To continue developing our widget we must activate our plugin by clicking Activate to the right of the plugin entry.

Activate plugin

Creating widget structure

There are different ways to create a Wordpress widget. I prefer creating it as a static class, but the downside of this method it that our widget will support php5 only, anyway I believe, that support for php4 can already be dropped. So let’s create our main class, that will contain all widget methods.

error_reporting(E_ALL);

add_action
("widgets_init", array('Widget_name', 'register'));
class Widget_name {
function control(){
echo
'I am a control panel';
}
function widget($args){
echo $args
['before_widget'];
echo $args
['before_title'] . 'Your widget title' . $args['after_title'];
echo
'I am your widget';
echo $args
['after_widget'];
}
function register(){
register_sidebar_widget
('Widget name', array('Widget_name', 'widget'));
register_widget_control
('Widget name', array('Widget_name', 'control'));
}
}

Our plugin should not throw any level errors (even notices), so we should turn error reporting on while we are developing. We will remove this line when the widget will be finished.

The add_action function hooks our register method to an widgets_init event. You can read about it in Wordpress codex. It takes the action hook name as its first parameter and the callback function as a second parameter. You should definitely read about callbacks in php manual.

To make widget appear in widgets menu in Wordpress we must register them first, we do that with our register method which creates a widget itself and a control panel for it.

The before_widget, after_widget, before_title and after_title in widget method are required for compatibility with various themes.

Activate widget

Navigate to widgets page in administration area and activate it. To do that press add button next to your widget. It should appear at current widgets column, you can press edit button next to it too see the control panel. Don’t forget to press save changes button!

The text from your widget method should appear in your blog sidebar.

Your widget in sidebar

Saving Widget Data to the Database

Most WordPress Widgets will need to get some input from the site owner or blog users and save it between sessions, for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions. There are two basic methods for saving Widget data in the database.

WordPress Options

This method is appropriate for storing relatively small amounts of relatively static, named pieces of data - the type of data you’d expect the site owner to enter when first setting up the Widget, and rarely change thereafter. Option values can be strings, arrays, or PHP objects (they will be “serialized”, or converted to a string, before storage, and unserialized when retrieved). Option names are strings, and they must be unique, so that they do not conflict with either WordPress or other Plugins. Here are function you will need to modify options.

add_option($name, $value);

update_option
($name, $new_value);
delete_option
($name);

Create a custom database table

This method is appropriate for data associated with individual posts, pages, attachments, or comments — the type of data that will grow as time goes on, and that doesn’t have individual names. See Creating Tables with Plugins for information on how to do this.

Plugin Installation

If you need to install default data for your widget it is best to use activation hook. It takes 2 parameters. First one is a path to the main plugin file inside the wp-content/plugins directory. And the second one is the function to be run when the plugin is activated. Any of PHP’s callback pseudo-types will work. We will add activate method that will install default data for our widget.

error_reporting(E_ALL);

add_action
("widgets_init", array('Widget_name', 'register'));
register_activation_hook
( __FILE__, array('Widget_name', 'activate'));
register_deactivation_hook
( __FILE__, array('Widget_name', 'deactivate'));
class Widget_name {
function activate(){
$data
= array( 'option1' => 'Default value' ,'option2' => 55);
if ( ! get_option('widget_name')){
add_option
('widget_name' , $data);
} else {
update_option
('widget_name' , $data);
}
}
function deactivate(){
delete_option
('widget_name');
}
function control(){
echo
'I am a control panel';
}
function widget($args){
echo $args
['before_widget'];
echo $args
['before_title'] . 'Your widget title' . $args['after_title'];
echo
'I am your widget';
echo $args
['after_widget'];
}
function register(){
register_sidebar_widget
('Widget name', array('Widget_name', 'widget'));
register_widget_control
('Widget name', array('Widget_name', 'control'));
}
}

Creating widget control panel

We should use our control method for displaying and updating form with widget options. Here is a basic template for it.

function control(){

$data
= get_option('widget_name');
?>
<p><label>Option 1<input name="widget_name_option1"
type
="text" value="" /></label>p>
<p><label>Option 2<input name="widget_name_option2"
type
="text" value="" /></label>p>
php
if (isset($_POST['widget_name_option1'])){
$data
['option1'] = attribute_escape($_POST['widget_name_option1']);
$data
['option2'] = attribute_escape($_POST['widget_name_option2']);
update_option
('widget_name', $data);
}
}

You should be able to access it on the widgets page.
Widget options

Conclusion

I hope this tutorial gave you all the information you need to build your first Wordpress widget. If you have something to add or found an error, please feel free to post a comment below. And I want to add that Wordpress codex is a great source of information.
courtsy: http://valums.com


Thursday

Create Custom WordPress Theme

In this tutorial, I will explain the basics of how WordPress theme works and show you how to convert a static HTML template into a theme. No PHP skill is required, but you need Photoshop and CSS skills to create your own design.

1. The Blog Frontend

Before you start, let’s take a look at the WordPress default theme and see how it is structured. Take note of the elements (header, post title, search form, navigation, footer, etc.).

Default Frontpage (index.php)

Default Single (single.php)

2. Photoshop Mockups

Based on the information gathered from the default theme, design a Photoshop mockup of your blog. Here I’m using GlossyBlue, one of my free WordPress themes, as an example.


3. HTML + CSS

After the PSD design is done, create a static HTML+CSS template of each page.

Why Create a Static HTML File First?

Mainly because it will make the development process a lot easier. I usually create a

HTML file for every template that I need, test it across all browsers, validate both HTML and CSS markups, then all I have to do is cut & paste the WordPress code. By doing so, I don’t have to worry about HTML or CSS bugs during my theme making process.

4. How WordPress Theme Works

If you go the default theme folder (wp-content/themes/default), you should see many PHP files (called template file) and one style.css file. When you are viewing the front page

, WordPress actually uses several template files to generate the page (index.php << header.php, sidebar.php, and footer.php).


5. Duplicate The Template Files

Copy the GlossyBlue HTML folder into the wp-content/themes folder. Then, go to the defaultcomments.php and searchform.php file to the glossyblue folder. theme folder, copy the

6. Style.css

Go to the WordPress default theme folder, open the style.css file. Copy the commented code at the top and paste it to the GlossyBlue style.css file. Change the theme name and the author information as you desire.

theme name and author's information

7. Splitting The Files

Now you need to understand where to split the file into several files: header.php, sidebar.php, and footer.php. The image below shows a simplified version of my index file and how the markups should split.

splitting files

8. Header.php

Open the index.html file. Cut from the top to where the ends, paste it in a new PHP file, and save the file as header.php.

header code

Go to the default theme folder, open the header.php. Copy and replace the tags where it requires PHP code (Template Tag): , stylesheet,

, and
.

replace code

Navigation Menu (wp_list_pages)

Replace the

  • tags in the
  • Sarvottom - The Best Open Source Web Development and BPO

    Monday

    Fiat Chooses PHP and Zend to build and web-enable their Fiatlink system

    Overview

    Fiat Group SpA is a diversified global company in business for over a century and is one of the top fifteen automobile manufacturers in the world, even larger than Daimler AG. Producing more than 85% of the automobiles that the Fiat Group manufactures and sells, the Fiat Group Automobiles SpA (FGA) subsidiary produces about 1.98 million automobiles/year. Over 42,000 Fiat users channel over $30 Billion (USD) in revenue (24 billion euros) through their PHP-based Fiatlink system which is now the primary access point for all of FGA's dealers and service centers to enter car orders and access information across the Fiat Auto enterprise. This is business-critical PHP.

    Improving sales performance and customer relations by exploiting back-end and point-of-use technology in the sales, service, and support processes they engage in was the goal for Fiat. Fiatlink addresses both sales and after sales that FGA processes, and currently handles 100% of the ordering and logistics and 65% (being rapidly built-out to 90%) of the vehicle customization & customer offers process, including essentially all CRM functions for Fiat, and will be completely rolled out to all of their markets in Europe in 2008.

    Originally slated to address just car ordering processes (customization of cars, ordering parts, etc.), Fiatlink is now used to additionally handle all dealer and FGA related processes from logistics to sales leads management, offering an integrated platform for all sales and post-sales processes.

    www.fiat.com
    The Challenge

    Fiat’s sales & customer support systems were not as up-to-date as Fiat innovation policies mandated, were spread across several disparate solutions, and there was no one place that all Fiat dealers and service centers could go to manage all the daily activities that are necessary for communication between FGA’s central headquarters and dealer services. Also, the previous system was built upon a traditional client-server model which meant long activation times, physical infrastructure maintenance problems, and very difficult to use user interfaces. This represented a significant drag on potential revenue opportunities for Fiat. They needed a way to rapidly develop and deliver new and enhanced functionality to their dealers. PHP was an ideal solution for this.

    “At the beginning we also considered Java as a development solution & language” says Roberto Fileni, Fiatlink’s Technical Architect, “but the main project goals were quick implementation and the PHP learning curve is much easier than with Java. In addition, Fiat Group’s IT division has a solid open-source technologies background. That also helped drive the choice for PHP.”
    The Business Case: Integrate 15 Disparate Applications into SSO Portal

    Fiat has integrated more than 15 different applications using PHP as the ‘glue’ to provide a responsive and integrated single-sign-on (SSO) portal for their 42,000 users to access myriad systems (B2C) in the Fiat Group Automobiles SpA enterprise. These include: logistics/planning systems, business management, training, CSI, post-sales support, warranties, marketing programs, CRM, and financing systems, both directly and in an integrated process environment.

    Because of the fast delivery that a PHP-based solution could provide to their Fiatlink users, Fiatlink is quickly becoming the primary way that all users interact with Fiat’s applications, worldwide.

    Fiat began with a LAMP-based prototype, but with the requirement that this needed to quickly be transformed into a production-ready business engineered solution. Porting to Oracle quickly after prototyping was another requirement. PHP fit their needs exactly. They are now building all of their code using web application “design pattern” standards like MVC, easy to do in PHP 5 where object-orientation is fully supported by the language and is now an industry standard practice for PHP.
    “When we performed a detailed analysis and were able to outline it in detail, we saw how widespread & diverse our user network of dealers and technical/service support users were, and that we needed to constantly adapt to, change, and create new and added features and functionality,” said Calì. “That’s the primary reason why we chose a PHP-based technology stack; PHP is a well-known language for building web-delivered solutions with versatility and reliability and that allows us to scale and build-out new functionality in a fraction of the time it would take us with other solutions.”
    -- Nunzio Calì,
    IT Director,
    Fiat Group Automobiles SpA
    The Bottom Line: Money & Time Saved Using Zend
    One of the key savings that Fiat Group Automobiles SpA made by using Zend’s web application server was the ability to save two (2) person-years worth of tested and already running Java business logic. Rewriting that code, not to mention testing and deploying it into a running application was untenable. Instead, by using Zend Platform, the Zend web application server, and the functionality it contains called Zend Java Bridge, Fiat was able to deploy their already tested and written Java business logic without needing to run an additional expensive WebSphere application server. This resulted in less moving parts to worry about, adminstrate, test, fix in production settings, and meant they also didn’t need to rewrite already running, tested code. Two person-years of code, plus testing, deployment, and administrative overhead: Estimated savings: €300,000 (USD ~ $450,000).

    Conclusion: PHP is ready for business-critical solutions
    PHP is an ideal solution for large, modern enterprises looking to rapidly deploy new and added functionality for their users. Adopting an open-source solution like PHP strategically knowing that in addition to the vibrant open-source community, Zend Technologies is also standing behind the platform provides peace-of-mind when utilizing open-source technology with lower TCO. Supporting tools like the Zend Studio IDE, the Zend application server and more, plus global services consulting and training from Zend's professional services experts all add up to make PHP more than ready for enterprise solutions.

    courtsy: http://www.zend.com

    Beyond Spot-Checking: Why LLM Applications Require Specialized Evaluation

      images generated by meta ai Building applications with Large Language Models (LLMs) feels deceptively fast at first. A single engineer can...