Archive

Author Archive

When JOINs fail to work

May 6th, 2012

Any developer, junior or senior, should know and understand the basic rules of database normalization since they are the foundation of relational DBMS. Edgar Codd introduced the concept in 1970 and since then, most of the architectures have been following his rules. However, for high-traffic websites, sometime de-normalized is better than normalized, resulting in faster queries, less swap space and less storage space.

Although this post is not exactly about normalization, another common recommendation is to use a join rather than multiple single queries. In other words, rather than doing “select * from a where condition1” then “select * from b where condition2”, if a and b are in a relationship, it’s better to usually run a query like “select * from a inner join b on a.id = b.aid where conditions”. A classic example is when using categories for a certain object, say movies. Let’s say each movie can have a category and you want to display a list of all movies and the category that movie is in. Some developers might write the following php code:

connect_to_database();
$rs = mysql_query('select * from movies');
while( $row = mysql_fetch_array($rs) ) {
  $rs2 = mysql_query('select * from categories where category_id = ' . $row['category_id'];
  $row2 = mysql_fetch_array($rs2);
  $category = $row2['category_name'];
  echo $row['name'] . "<br />Category: " . $category . "<br /><br />";
}

but there’s a simpler and (most of the time) better approach:

connect_to_database();
$rs = mysql_query('select * from movies m inner join categories c on c.category_id = m.category_id');
while( $row = mysql_fetch_array($rs) ) {
  echo $row['name'] . "<br />Category: " . $row['category_name'] . "<br /><br />";
}

The first approach generates 1 + N queries, where N is the number of movies. If N is a big number, things might take a while… The second approach only takes 1 query, leaving the hard part to the internal RDBMS engine. Well, sometimes, in certain scenarios, the first version is the right choice. It’s THE solution.

Let’s assume there are 4+1 tables – the main one, call it objects, one for tags, one for categories, another one called hits which will track the number of times a certain object has been seen by a user, and the last one for storing the n-to-n relationship between tags and objects, call it >code>object_tags. The ERD is rather simple:

Also, let’s assume we want to show a list of objects, with all their tags, their current category and the number of hits it has. The results will be paginated, only showing 20 items per page. Simple, right? Anyone would tend to write something like this for the first page:

SELECT * FROM objects o 
INNER JOIN categories c ON c.category_id = o.category_id
INNER JOIN object_tags ot ON ot.object_id = o.object_id
INNER JOIN tags t ON t.tag_id = ot.tag_id
INNER JOIN hits h ON h.object_id = o.object_id
LIMIT 20

This was what I wrote too, more or less. However, after spending many hours trying to figure out why that page was loading in more than 100 seconds, whenever it was loading at all, I’ve learned that sometimes it’s better to break the rules and not follow any recommendations. So I tried the following code, and the results were staggering – less than 1s loading time:

$rs = mysql_query('select * from objects limit 20');
$categories = $tags = array(); //used for locally caching categories and tags
while( $row = mysql_fetch_array($rs) ) {
  if( !isset($categories[$row['category_id']]) {
    $rsCat = mysql_query('SELECT category_name FROM categories WHERE category_id = ' . $row['category_id'] . ' LIMIT 1';
    $rowCat = mysql_fetch_array($rsCat);
    $categories[$row['category_id']] = $rowCat['category_name'];
    unset($rowCat, $rsCat);
  }

  $objectTags = $toLoad = array();
  $rsObjTags = mysql_query('SELECT tag_id FROM object_tags WHERE object_id = ' . $row['object_id']);
  while( $rowObjTags = mysql_fetch_array($rsObjTags) ) {
    if( isset($tags[$rowObjTags['tag_id']]) ) {
      $objectTags[$rowObjTags['tag_id']][] = $tags[$rowObjTags['tag_id']];
    }
    else {
      $toLoad[] = $rowObjTags['tag_id'];
    }
  }
  unset($rsObjTags , $rowObjTags);

  if( count($toLoad) ) {
    $rsTags = 'SELECT tag_id, tag FROM tags WHERE tag_id IN (' . implode(',', $toLoad) . ') LIMIT ' . count($toLoad);
    while( $rowTags  = mysql_fetch_array($rsTags) ) {
      $tags[$rowTags['tag_id']] = $rowTags['tag'];
      $objectTags[$rowTags['tag_id']][] = $rowTags['tag'];
    }
  }
  unset($toLoad, $rsTags, $rowTags);

  $rsHits = 'SELECT today_hits FROM hits WHERE object_id = ' . $row['object_id'] . ' LIMIT 1';
  $hits = mysql_fetch_array($rsHits);

  //ready to display the data
  echo $row['object_name'] . ' is in category ' . $categories[$row['category_id']] . '<br />';
  echo 'Tags: ' . implode(', ', $objectTags) . '<br/>';
  echo 'Hits today: ' . $hits['today_hits'] . '<hr />';
}

I hope there aren’t too many mistakes in the code, I wrote everything in here without actually testing it.

Seems like a lot of work and totally not optimized for something quite straight-forward. However, let’s assume once more that the tables above have the following number of records:
objects – 50,000
categories – 500
tags – 100,000
objects_tags – 250,000
hits – 20,000,000

In this case, 4 joins would result in a huge dataset, requiring a lot of memory, and eventually ending up on the disk. Also, the LIMIT doesn’t help at all, since the dataset is truncated at the end, after scanning all the necessary rows. However, in the unoptimized version we do benefit from the LIMIT, by only getting a fixed set (20 rows) from 50k rows. The rest of the queries are acceptable because they are all primary key based, they are using “LIMIT” as well (3 out of 4), and because their number is rather small – somewhere between 45 and 80 queries.

Hope this helps someone some day. I’d like to know your thoughts, what would have you done? Any other quick fixes for this problem?

MySQL ,

Hardening OpenX

April 18th, 2012

There are times when your website or application might get hacked. The usual reasons include weak passwords, outdated software or poor code (especially on validating user input). The same apply to OpenX – your ad server can be hacked due to an outdated version of OpenX, weak passwords, insecure server settings or a combinations of the above. Most common hacks add an iframe or script to the banner page distributing malware (a virus, trojan horse, or similar). This can get your website (the one that uses your infected openx server) to be blocked on all major browsers and most of the search engines.

To decrease the chances of having your openx hijacked, it’s recommended to follow these quick and easy steps. You’ll notice that some of them apply to any web application, like using strong passwords (at least 6 chars, using both uppercase and lowercase letters, digits and special chars).

Things to do with your OpenX installation
1. Always update the application and plugins to the latest versions. This ensures your ad server has the latest patches and security fixes, but it also makes hacking a bit more difficult. You can check if you have the latest version by going to Configuration / Product Updates in the OpenX administration interface.

2. If your administrator username is admin or administrator (or anything similar), change it to something less common, like your first name or last name. This cannot be done from the openx admin interface, but it can be done directly in mysql (using phpmyadmin for instance) – the table you are looking for is [table_prefix]_users

3. If there are other users who manage the inventory, create separate accounts for them and make them advertisers, not admins. Keep the admin account safe and do not share it with anyone.

4. If you only server banners on your website(s), you can remove all users from Advertisers and Websites. As a general rule, when you create a new advertiser, do not also create a username. If you don’t offer OpenX access to advertisers, there’s really no point in adding new users.

5. Always use the logout link to log out, instead of just closing the tab or window. This prevents session hijacking or keeping an active session on a public computer.

6. Disable all plugins that you don’t use

Things to do on the server side
1. Setup the openx database with its own username and use a really strong password. Make sure the user is only allowed to connect from the server that runs openx (where your web server is located) – this is usually the same machine, so localhost will be just fine. The password should be really strong. You can use an online password generator tool, like this one: http://www.pctools.com/guides/password/

2. Add an extra layer of authentication, using http basic auth for example. Follow the instruction in the links below:
http://httpd.apache.org/docs/2.0/howto/auth.html
http://httpd.apache.org/docs/2.0/programs/htpasswd.html

3. Change the database structure of the banner’s table so it doesn’t allow append & prepend codes anymore. You can do this by changing the two fields in the banners table ([table_prefix]_banners) from varchar(255) to varchar(0) (through phpmyadmin or the cli):
alter table openx_banners change append append varchar(0);
alter table openx_banners change prepend prepend varchar(0);

3a. Change the database structure of the zone’s table so it doesn’t allow append & prepend codes anymore – thanks Stefan for suggesting this.
alter table openx_zones change append append varchar(0);
alter table openx_zones change prepend prepend varchar(0);

Make sure to replace “openx” with the table prefix you use.

4. Set the proper permissions to all files & folders – all files should not be writable by the server by default, except the var/, plugins/ and www/images/ folders.
Your configuration file, located in var/, should not be writable:
chmod 0444 [domain].conf.php

5. Remove all installation files

What if I am already infected?
It’s important to find out all infected files or database entries and then figure out how they got there. Do not remove anything befire understanding how you got infected in the first place. You can disable the openx server temporarily (by adding this line in an .htaccess file in the folder www/delivery: deny from all).
Once you know where the security breach is, fix it, harden the server, change passwords (just to be sure), clean up the infected data and remove the deny all line from the .htaccess file.

We can also help you cleaning, securing and upgrading your openx installation(s) – contact us.

Security ,

Installing Memcache Server for PHP on Windows

February 15th, 2012

Memcached is a free open source, high-performance, distributed memory object caching system. It is currently used by a lot of websites, including Flickr, Twitter, Youtube, Digg and WordPress.

I’ve been using memcached on a few production servers, but never thought it could come in handy on a Windows development machine – in fact I didn’t even thought it was available on Windows. So, a few days ago, while working on yet another Magento project, I ran a Google search for “memcache windows” and it turned out there are a few Win32 ports of the original version. Cool! It can be used on Windows, now all I need is to find the right PHP extension.

Here’s a step-by-step tutorial on how to get memcached running in PHP on a Windows box. There’s are a bunch of really good tutorials out there, but I think another could only be helpful.

1. Go to http://splinedancer.com/memcached-win32/ and download memcached. I’ve used the 09.03.2008 binaries, memcached 1.2.4.
You can also use v1.2.6 that you can download from http://code.jellycan.com/memcached/ – I’ve used this one to update from the previous 1.2.4 and I can confirm that it works.

2. Unzip the downloaded file to any folder (i.e. C:/memcached). I’ve saved in the same place where I have Apache, MySQL and PHP.

3a. If you’re on Windows Vista, navigate to your memcached folder, right click on memcached.exe and click Properties, then click the Compatibility tab. In here, check the “Run this program as an administrator” checkbox.

3. Install the service by running memcached.exe -d install from the command line. (you should be in the folder where you unzipped the file(s), ie: c:/memcached)

By default, memcached has 64M available for caching and runs on port 11211. If you need to change any of these you can do it by editing the Registry – open regedit then search for HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/memcached Server. Change the ImagePath entry from "C:\memcached\memcached.exe" -d runservice to "C:\memcached\memcached.exe" -d runservice -m 256 -p 11222". This gives you 256 megs of memory and change the port to 11222 (on a development machine you probably don’t need to change the port, but who knows). See the full list of memcached options – not sure which ones apply to the Windows version too.

4. Now, that the service is installed and configured, let’s start it: memcached.exe -d start
To test that memcached is running you can try telnet’ing – telnet localhost 11211 (use the port you configured the service to listen to). If you can connect on that port, everything is fine.

5. Memcached is installed, but we need to use in PHP, so we need an extension. Here’s a list of sites where you can download the dll from:
http://downloads.php.net/pierre/
http://www.pureformsolutions.com/pureform.wordpress.com/2008/06/17/php_memcache.dll
http://kromann.info/download.php?strFolder=php5_1-Release_TS&strIndex=PHP5_1
shikii.net/blog/downloads/php_memcache-cvs-20090703-5.3-VC6-x86.zip

I had to install a VC6 dll, so I’ve downloaded the last one. Unzip it and put it in your php extensions folder. If you don’t know where this folder is, try this command: php -i | find "extension_dir". Add the dll in there, then open php.ini (to find it, you can run php -i | find "Loaded Config") and at the end add something like this:

[PHP_MEMCACHE]
extension=php_memcache.dll

Now restart Apache.

6. To test that memcached can now be used in PHP, use the following snippet:

$memcache = new Memcache;
if( !$memcache->connect('localhost', 11211)) { //change 11211 with the port your memcached is configured to listen to
  die('Could not connect!');
}

echo '
';
print_r($memcache->getStats());

If you see an array with a bunch of data in it, you’ve done it. If not, something went wrong at some point. Make sure memcached is running, then make sure you’ve got the correct php settings and extension.

As I mentioned at the beginning of the post, installing memcached was something that just hit me while working on a Magento project – for those familiar with Magento, you know how slow it can be sometimes, especially when you need to constantly refresh the pages to check html/js/css changes. So, I thought memcached would help speed up the parts on which I wasn’t working on – everything except layouts and html block cache. And so it did, development seems MUCH easier now – but all about this in another post, soon to come.

Many thanks for helping me figure this out and (hopefully) speeding up development to:
http://splinedancer.com/memcached-win32/
http://pureform.wordpress.com/2008/01/10/installing-memcache-on-windows-for-php/
http://shikii.net/blog/installing-memcached-for-php-5-3-on-windows-7/

PHP , ,

Workaround for attribute store labels not being displayed in Magento

February 12th, 2012

Here’s a quick workaround for a rather strange issue – sometimes, calling $attribute->getStoreLabel() returns null, although everything looks fine in the admin and in the database. It might be something that is slipping my mind, or it might be a bug, not really sure. However, I had to deal with it and come up with a fix, so I’d thought I’d share.

$_aIds = array();
foreach( $prod->getAttributes() as $attribute ) {
	//need the attribute_id which is missing from the attribute object
	if( !isset($_aIds[$attribute->getAttributeCode()]) ) {
		$_aIds[$attribute->getAttributeCode()] = $attribute->getIdByCode('catalog_product', $attribute->getAttributeCode());
	}
			
	//if there's not store_label try to set it
	if( !$attribute->getStoreLabel() ) {
		$labels = $attribute->getResource()->getStoreLabelsByAttributeId( $_aIds[$attribute->getAttributeCode()] );
		if( array_key_exists(Mage::app()->getStore()->getStoreId(), $labels)) {
			$attribute->setStoreLabel( $labels[Mage::app()->getStore()->getStoreId()] );
		} 
		else {
			$attribute->setStoreLabel( $attribute->getFrontendLabel() );
		}
	}
}
// end workaround

Applies to Magento 1.5.x

Magento ,

Prototype 1.6, Event.stop and IE9 – Quick patch

November 30th, 2011

For those of you using Prototype 1.6 (or Magento prior 1.6), you might wonder why event.stop() or Event.stop(event) doesn’t work in Internet Explorer 9. Here’s a quick explanation:

IE 9 makes major changes to the event system. We had to rewrite the
event code in 1.7 to support it. You can either (a) upgrade to 1.7;
(b) force your site into compatibility mode [1].

So it’s been fixed in 1.7, but what if I can’t upgrade to 1.7 and don’t want to render my website in compatibility mode? Well, after a couple of hours trying to sort this out, here’s quick (and dirty) patch for Prototype 1.6.0.3. Download Prototype 1.6.0.3 Event.stop IE9 fix (448 bytes)

Also, for further reading, here are two external links that you might find useful for this issue.

Note/Disclaimer: This has only been tested on Prototype 1.6.0.3. Use it at your own risk.

Javascript , ,

Strange Prototype’s Class.create behavior

November 1st, 2011

A few more months and it would’ve been a year since the last post. Worry not, this blog hasn’t died – and just to make sure I don’t forget what I want to write, I’ve already prepare a few articles. So stay tuned!

But enough with the intro and let’s see what this article is about: Prototype (http://www.prototypejs.org/), not really my favorite javascript framework, but since Magento relies on it, I need to be able to use it and write proper code (I don’t believe in mixing frameworks either).

The scenario is rather simple – create a “class” called Stuff and then instantiate two objects of that class.

var Stuff = Class.create({
	data: {},
	x: null,
	y: [],
	
	initialize: function() {}
});

var a = new Stuff();
var b = new Stuff();

So far so good, because the code does nothing, but let’s add the following:

a.data.x = 1;
a.x = 5;
a.y.push(3);

What would you expect b to contain? From my (lack of) knowledge, I would say b.data is an empty object, b.x is null and b.y is an empty list/array. At least that’s how it goes in other programming languages, such as PHP. Well, this doesn’t happen here. If you do console.log(b) you’ll get:

data	Object { x=1}
x	null
y	[3]

In other words, object and array attributes have the same reference, or point to the same object. I would’ve said that the variables a and b are pointing to the same object, if a.x was the same as b.x, but b.x is still null, while a.x is 5.

Bug, feature or normal behavior, this can still be very annoying – I spent about an hour trying to figure out why two objects of the same “class” had the same settings when they were clearly configured differently. Hope this comes in handy at some point.

Tested on prototype v1.6.0.3 & v1.6.1.

Javascript ,

Patching the Magento USPS module

January 20th, 2011

Since their last update on Jan 3rd, 2011 USPS has stopped working on all of my Magento distro’s. The reason for that is a change in USPS’ response XML values. Magento has its part of blame here, first for not patching it immediately (which again shows how much they care about the CE users) and second for not coding it properly in the first place – they’re using the method name (i.e. Express Mail) to see if that method is allowed from the admin, instead of using the CLASSID attribute.

This issue has been reported on magentocommerce.com bug tracking system and it’s also discussed in the forum. USPS makes it clear that they’ll discontinue all API versions prior RateV4 ad IntlRateV2:
“All Rate Calculator API integrators are encouraged to migrate to the latest API versions (RateV4, IntlRateV2):
RateV4 and IntlRateV2 will be the only Rate Calculator API versions to offer the full range of new products and functionality
Rate, RateV2, RateV3 and IntlRate will be retired in May 2011, requiring all integrators to migrate to the latest versions”

As explained on the forums, the fix is quite simple, as USPS only added the &lt;sup&gt;&reg;&lt;/sup&gt; which is the encoded (twice 🙂 ) version of the registered sign in a sup tag. Magento values are defined without those so when the code tries to match them it fails. All you have to do is clean that string and you’re good to go. I don’t like to modify core files so the fix involves copying app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php to app/code/local/Mage/Usa/Model/Shipping/Carrier/ and working on the local version of Usps.php. Strip the special chars:

$mailService = str_replace('&reg;', '', strip_tags(htmlspecialchars_decode(htmlspecialchars_decode((string)$postage->MailService))));

and

$svcDescription = str_replace('&reg;', '', strip_tags(htmlspecialchars_decode(htmlspecialchars_decode((string)$service->SvcDescription))));

 

Here’s the archive with the patch. Just download it and unzip it in the root of your Magento distribution. Download USPS patch for Magento 1.4.2.0 (8.59 kB)

 

Note: This patch applies to Magento CE 1.4.2.0. For all other versions you will have to do it manually as explained above.

 

Magento, PHP , ,

Anatomy of a Magento extension

January 5th, 2011

Magento Commerce has been on the OSS “market” for a while now and I see more and more developers, designers and of course store owners migrating their ecommerce sites to Magento or installing it for their new stores. I’ve been coding on Magento since its beta 0.6 version, actually my first integration was based on this beta. I’ve been advised not to use the beta and they were right. However, I had my reasons for recommending it, using it and somehow advocating for that fresh, promising open source piece of software. In the meanwhile, it turned out I was right – it’s one of the most complete, scalable & feature-rich free ecommerce solution. Not the easiest to integrate or use, not the smoothest or lightweight, but it’s come a long way and it still have room for improvements.

One of the things I liked from the start (as a developer) was the ability to extend it in a very simple and loosely coupled way (unlike other solutions). Adding the OOP and design patterns made it perfect for my way of thinking. And I think this is the way to go for any major application, even if it might seem cluttered or with a steep learning curve at a first glance. I remember one of the first problems I faced was module creation – I was adding all my code in the core/Mage folder, I was overwriting a lot of the core code although I knew it was bad and so on. However, once I understood how to create a module, things became clearer and much simpler. So here’s a beginner’s guide to creating a new module. Although it’s meant for beginners, you should know the basic folder layout (skins, library, js, apps).

All Magento code resides in app/code and the lib folder. If you check app/code you’ll notice three subfolders: community, core, local. You should be adding your stuff in local or community (usually only when it is a community contribution). So let’s create our first module. I’ll use the namespace mandagreen and the module will be called HelloWorld. For this I need to create the following folders under app/code/local:
Mandagreen/HelloWorld

To keep things simple, in this example we’ll be creating one Block, one Helper and one Model – no controllers & no Resource Models. Here’s where each of these will reside:
blocks – app/code/local/Mandagreen/HelloWorld/Block
helpers – app/code/local/Mandagreen/HelloWorld/Helper
models – app/code/local/Mandagreen/HelloWorld/Model

Create these three folders and then also create a new etc folder. The structure will then look like this:

    app/code/local/Mandagreen/HelloWorld/Block
    app/code/local/Mandagreen/HelloWorld/etc
    app/code/local/Mandagreen/HelloWorld/Helper
    app/code/local/Mandagreen/HelloWorld/Model

The etc folder holds configuration information – in this case we’ll focus only on the module configuration file, which is config.xml. Let’s create it and start adding some xml into it:

<?xml version="1.0"?>
<config>
	<modules>
		<Mandagreen_HelloWorld>
			<version>0.0.1</version>
		</Mandagreen_HelloWorld>
	</modules>

	<global>
		<models>
			<helloworld>
				<class>Mandagreen_HelloWorld_Model</class>
			</helloworld>
		</models>
 
		<blocks>
			<helloworld>
				<class>Mandagreen_HelloWorld_Block</class>
			</helloworld>
		</blocks>

		<helpers>
			<helloworld>
				<class>Mandagreen_HelloWorld_Helper</class>
			</helloworld>
		</helpers>
	</global>

	<frontend>
		<layout>
			<updates>
				<helloworld>
					<file>mg_helloworld.xml</file>
				</helloworld>
			</updates>
		</layout>

		<translate>
			<modules>
				<Mandagreen_HelloWorld>
					<files>
						<default>Mandagreen_HelloWorld.csv</default>
					</files>
				</Mandagreen_HelloWorld>
			</modules>
		</translate>
	</frontend>
</config>

That’s a lot, isn’t it? 🙂 No worries, I’ll explain. Under the main node (config), youll usually need the global node. The modules node is being used to hold mode info about the current module, maybe dependencies and so on. The frontend node is usually used for defining layout handlers and translation files, but they can do more than that. In this example, we’re gonna have our own layout file called mg_helloworld.xml – you can use any name on it (as long as it’s unique), but I prefer to namespace it as well. Also, I’ve defined a translation file Mandagreen_HelloWorld.csv which needs to be created in app/locale/en_US (or whatever your default locale is).

The global node defines all the classes you’ll be using, in this case helpers, models and blocks. You can see that they are defined the same way, but in different locations: <helpers />, <models /> and <blocks />. Let’s use the helpers node as an example xenical orlistat.

		<helpers>
			<helloworld>
				<class>Mandagreen_HelloWorld_Helper</class>
			</helloworld>
		</helpers>

The helloworld node defines a handle and you should be careful to always use unique names. If you’re not sure if a certain name exist, namespace it (mghelloworld for example). This handle will be used to instantiate models, call helpers or use blocks using the Magento factory. For example, for models, you’ll be using Mage::getModel('helloworld/modelname'); instead of new Mandagreen_HelloWorld_Model_Modelname();. Same with helpers, inside a block template – $this->helper('helloworld')->someMethod();.
The other node, class is being used to define the namespace of the class name. In the example above, the name of the Modelname class has to being with Mandagreen_HelloWorld_Helper. A few examples might help:

  • Mandagreen_HelloWorld_Model_Salute, will be found in Mandagreen/HelloWorld/Model/Salute.php and can be accessed via Mage::getModel('helloworld/salute')
  • Mandagreen_HelloWorld_Model_Salute_Hi, will be found in Mandagreen/HelloWorld/Model/Salute/Hi.php and can be accessed via Mage::getModel('helloworld/salute_hi')
  • Mandagreen_HelloWorld_Helper_Help, will be found in Mandagreen/HelloWorld/Model/Help.php and can be accessed via Mage::helper('helloworld/help')

Now that we explained the config file, let’s move on to actually creating the classes and code. I’ll use the example above and create the following files:

Mandagreen/HelloWorld/Block/Standard.php

<?php

class Mandagreen_HelloWorld_Block_Standard extends Mage_Core_Block_Template {
    function getSomething() {
          return Mage::getModel('helloworld/salute')->getName();
    }
}

Mandagreen/HelloWorld/Helper/Help.php

<?php

class Mandagreen_HelloWorld_Helper_Help extends Mage_Core_Helper_Abstract {
    function shouldSayHi() {
          return true;
    }
}

Mandagreen/HelloWorld/Model/Salute.php

<?php

class Mandagreen_HelloWorld_Model_Salute extends Mage_Core_Model_Abstract { //or Varien_Object or none
    function getName() {
          //do some heavy logic here
          return 'John';
    }
}

One more file is required for the translations to work with this module – a “default” Data helper, defined in Mandagreen/HelloWorld/Helper/Data.php like this:

class Mandagreen_HelloWorld_Helper_Data extends Mage_Core_Helper_Abstract {}

We have the classes but we also need to use them in a template, so let’s create standard.phtml in app/design/frontend/default/default/template/helloworld (create all additional folders if needed). Also, create mg_helloworld.xml under app/design/frontend/default/default/layout.

For the template, things are very easy:

<div style="background: red; padding: 20px;">
	<?php if( $this->helper('helloworld/help')->shouldSayHi() ): ?>
	Hello <?php echo $this->getSomething(); ?>
	<?php else: ?>
	Can't say anything...
	<?php endif; ?>
</div>

while for the layout we’ll use this approach:

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="content">
            <block type="helloworld/standard" name="helloworld" template="helloworld/standard.phtml" after="-" />
        </reference>
    </default>
</layout>

This should display “Hello John” at the end of the content area on most of the pages, including the homepage. But wait, before you try that you’ll have to enable the module in app/etc/modules. Create a file called Mandagreen_HelloWorld.xml with the following code:

<?xml version="1.0"?>
<config>
    <modules>
        <Mandagreen_HelloWorld>
            <active>true</active>
            <codePool>local</codePool>
        </Mandagreen_HelloWorld>
    </modules>
</config>

Clear all magento cache and refresh the page – your first module, up and running! And here’s the archive for this tutorial – Download Hello World Magento Module (2.99 kB)

Further/recommended reads:

Magento

Adding Customer Comments as Order Status Comments using Magento & OneStepCheckout

October 24th, 2010

A few days ago I got an email from someone asking me about adding the default customer comments in OneStepCheckout (www.onestepcheckout.com) as regular order comments. I thought I’d share this quick & simple hack with everyone, so here’s what you have to do:
Open app/code/local/Idev/OneStepCheckout/Helper/Data.php, and after

$observer->getEvent()->getOrder()->setOnestepcheckoutCustomercomment($orderComment);

add this line:
$observer->getEvent()->getOrder()->setState( Mage_Sales_Model_Order::STATE_NEW, true, $orderComment, false );

$observer->getEvent()->getOrder()->setState( 
    $observer->getEvent()->getOrder()->getStatus(), 
    true, 
    $orderComment, 
    false 
);

This will add the comments on the regular comments/statuses thread, as well as a customer comment. If you want to disable customer comments, just comment the original code.

Actually, this approach should also work with the out-of-the-box Magento one step checkout. Add an input on the last step, create a listener for

checkout_type_onepage_save_order

and use the same piece of code:

$observer->getEvent()->getOrder()->setState( $observer->getEvent()->getOrder()->getStatus(), true, $this->_getRequest()->getPost('order_comments'), false );

Note: Tested on Magento 1.4.1.0 & 1.4.1.1

Magento ,

Introducing Magento CSS & JS Minifier

September 15th, 2010

As the title says, I’m glad to announce my first public Magento extension (not yet added in the Connect repository). During my 3 years experience with Magento, I’ve worked on a lot of custom extensions, improvements & fixes, but most of them were client-specific, plus they weren’t designed to have a backend interface (with a few exceptions). This one, however, is entirely configurable from the Admin and it’s both simple and effective.

 

What it does

This quick optimizer parses all javascript & css files included on a page and removes all unnecessary characters. The most simple step is to remove spaces, tabs and new lines – but there’s more than just that. Of course, for small files compression is insignificant, but when you work with almost 600KB and around 30 requests, you can save a lot. Here’s a quick math on one of my Magento installs:

Javascript – 26 requests, 479 KB
CSS – 4 requests, 102 KB

With Magento’s default merging enabled:
Javascript – 1 request, 360 KB (not sure why this is smaller then the 26 summed up, but nvm)
CSS – 1 request, 108.2 KB (same for this one too, but again, nvm)

We’ve already saved 28 requests, which means less overhead – quicker download times for user, less stress on the server.

With the Minifier enabled:
Javascript is 255 KB, which means almost 47% compression
CSS is 92 KB, which means almost 10% compression

 

Advantages

 

Disatvantages

  • Need to write javascripts very careful, adding a semicolon after almost everything
  • Have to rewrite of Mage_Core_Model file
  • Have to override two Magento methods
  • Additional processing time (insignificant in my opinion)

 

Credits

This plugin wouldn’t exist if it weren’t for these two outstanding PHP projects:
Joe Scylla’s CssMin
Ryan Grove’s JsMin
Big thanks to both of them.

 

Download & Install


First, Download Minifier for Magento (31.03 kB), then unzip it and copy the app/ folder to your Magento root folder.

Logout from the admin if you’re already logged in, then login. Go to Cache Management, click on the “Flush cache storage” button, then go to Configuration > Developer and enable all the options, as shown in the attached screenshot. Go back to Cache Management and this time click on the “Flush Javascript/CSS cache”.

Go to your store frontend and behold, you’re now using compressed js’s and css’s.

Works on Magento 1.4+

Updated on May 31st, 2012 – all download links in this page refer to the latest version of the plugin. Some explanations on this post might be inaccurate. For the latest details please check new post called Updated version of the Magento CSS & JS Minifier

Magento , , ,